: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(cdp): hardcode hogflow queue to postgres-v2 (#58997)
Meikel Ratz07c788ea8582
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 5a250188792a..568565cabe16 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '../../tests/helpers/mocks/job-queue.mock'import { mockProducer } from '../../tests/helpers/mocks/producer.mock'import { mockFetch } from '../../tests/helpers/mocks/request.mock'@@ -80,7 +81,10 @@ describe('CDP API', () => {team = await getFirstTeam(hub.postgres)cdpDeps = createCdpConsumerDeps(hub)- api = new CdpApi(hub, cdpDeps)+ api = new CdpApi(hub, cdpDeps, {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })app = setupExpressApp()app.use('/', api.router())server = app.listen(0, () => {})@@ -781,7 +785,7 @@ describe('CDP API', () => {beforeEach(async () => {mockQueueInvocations = jest.fn().mockResolvedValue(undefined)- api['cyclotronJobQueue'] = { queueInvocations: mockQueueInvocations } as any+ api['hogflowQueue'] = { queueInvocations: mockQueueInvocations } as anyscheduleHogFlow = await insertHogFlow({id: new UUIDT().toString(),diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex ec1f44f98f44..6a054e2d0fef 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -31,7 +31,7 @@ import { HogExecutorExecuteAsyncOptions, HogExecutorService, MAX_ASYNC_STEPS } fimport { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'import { InvocationResultsService } from './services/invocation-results.service'-import { CyclotronJobQueue } from './services/job-queue/job-queue'+import { JobQueue } from './services/job-queue/job-queue.interface'import { GroupsManagerService } from './services/managers/groups-manager.service'import { HogFunctionManagerService } from './services/managers/hog-function-manager.service'import { EmailTrackingService } from './services/messaging/email-tracking.service'@@ -85,7 +85,8 @@ export class CdpApi {private invocationResultsService: InvocationResultsServiceprivate rerunJobManager: RerunJobManager | null = nullprivate cdpSourceWebhooksConsumer: CdpSourceWebhooksConsumer- private cyclotronJobQueue: CyclotronJobQueue+ private hogQueue: JobQueue+ private hogflowQueue: JobQueueprivate emailTrackingService: EmailTrackingServiceprivate recipientTokensService: RecipientTokensServiceprivate outputs: CdpOutputs@@ -93,7 +94,8 @@ export class CdpApi {constructor(private config: PluginsServerConfig,- private deps: CdpApiDeps+ private deps: CdpApiDeps,+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }) {const services = createCdpCoreServices(config, deps, 'cdp-api-redis')@@ -114,8 +116,9 @@ export class CdpApi {...deps,monitoringOutputs: services.outputs,})- this.cdpSourceWebhooksConsumer = new CdpSourceWebhooksConsumer(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = jobQueues.hogQueue+ this.hogflowQueue = jobQueues.hogflowQueue+ this.cdpSourceWebhooksConsumer = new CdpSourceWebhooksConsumer(config, deps, jobQueues)this.emailTrackingService = new EmailTrackingService(this.hogFunctionManager,this.hogFlowManager,@@ -142,8 +145,8 @@ export class CdpApi {}async start(): Promise<void> {+ // CdpSourceWebhooksConsumer.start() calls startAsProducer on both queuesawait this.cdpSourceWebhooksConsumer.start()- await this.cyclotronJobQueue.startAsProducer()// Rerun endpoints don't run the work — they just enqueue a wrapper// job onto the cyclotron-v2 'rerun' queue. A dedicated consumer@@ -160,9 +163,9 @@ export class CdpApi {}async stop(): Promise<void> {+ // CdpSourceWebhooksConsumer.stop() calls stopProducer on both queuesawait Promise.all([this.cdpSourceWebhooksConsumer.stop(),- this.cyclotronJobQueue.stop(),this.batchExportHogFunctionService.stop(),this.rerunJobManager?.disconnect() ?? Promise.resolve(),])@@ -620,7 +623,7 @@ export class CdpApi {const invocation = createHogFlowInvocation(triggerGlobals, hogFlow, filterGlobals)- await this.cyclotronJobQueue.queueInvocations([invocation])+ await this.hogflowQueue.queueInvocations([invocation])res.json({ status: 'queued', invocation_id: invocation.id })} catch (e) {diff --git a/nodejs/src/cdp/cdp-e2e.test.ts b/nodejs/src/cdp/cdp-e2e.test.tsindex 0080c729627d..8845c3fdc71d 100644--- a/nodejs/src/cdp/cdp-e2e.test.ts+++ b/nodejs/src/cdp/cdp-e2e.test.ts@@ -23,17 +23,18 @@ import {insertIntegration,} from './_tests/fixtures'import { CdpEventsConsumer } from './consumers/cdp-events.consumer'+import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'+import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'import { compileHog } from './templates/compiler'const ActualKafkaProducerWrapper = jest.requireActual('../../src/kafka/producer').KafkaProducerWrapper-describe.each(['postgres' as const, 'kafka' as const, 'hybrid' as const])('CDP Consumer loop: %s', (mode) => {+describe('CDP Consumer loop', () => {jest.setTimeout(20000)describe('e2e fetch call', () => {let eventsConsumer: CdpEventsConsumer- let cyclotronWorkerKafka: CdpCyclotronWorker | undefined- let cyclotronWorkerPostgres: CdpCyclotronWorker | undefined+ let cyclotronWorker: CdpCyclotronWorkerlet hub: Hublet kafkaProducer: KafkaProducerWrapper = undefined as unknown as KafkaProducerWrapper@@ -70,12 +71,6 @@ describe.each(['postgres' as const, 'kafka' as const, 'hybrid' as const])('CDP Chub.CDP_FETCH_RETRIES = 2hub.CDP_FETCH_BACKOFF_BASE_MS = 100 // fast backoffhub.CDP_CYCLOTRON_COMPRESS_KAFKA_DATA = true- hub.CYCLOTRON_DATABASE_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron'-- // If hybrid we enable the scheduling to PG which ensures we test that routing there happens- hub.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES = mode === 'hybrid'- hub.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING =- mode === 'hybrid' || mode === 'kafka' ? '*:kafka' : '*:postgres'// Include integration parsing as part of the e2e checkawait insertIntegration(hub.postgres, team.id, {@@ -116,32 +111,17 @@ describe.each(['postgres' as const, 'kafka' as const, 'hybrid' as const])('CDP C...HOG_FILTERS_EXAMPLES.no_filters,})- eventsConsumer = new CdpEventsConsumer(- {- ...hub,- CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: mode === 'hybrid' ? 'kafka' : mode,- },- createCdpConsumerDeps(hub, kafkaProducer)- )- await eventsConsumer.start()+ const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub)+ const postgresV2Queue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)- cyclotronWorkerKafka = new CdpCyclotronWorker(- {- ...hub,- CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'kafka',- },- createCdpConsumerDeps(hub, kafkaProducer)- )- await cyclotronWorkerKafka.start()+ eventsConsumer = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })+ await eventsConsumer.start()- cyclotronWorkerPostgres = new CdpCyclotronWorker(- {- ...hub,- CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres',- },- createCdpConsumerDeps(hub, kafkaProducer)- )- await cyclotronWorkerPostgres.start()+ cyclotronWorker = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub, kafkaProducer), kafkaQueue)+ await cyclotronWorker.start()globals = createHogExecutionGlobals({project: {@@ -170,13 +150,10 @@ describe.each(['postgres' as const, 'kafka' as const, 'hybrid' as const])('CDP C})afterEach(async () => {- const stoppers = [+ await Promise.all([eventsConsumer?.stop().then(() => console.log('Stopped eventsConsumer')),- cyclotronWorkerKafka?.stop().then(() => console.log('Stopped cyclotronWorkerKafka')),- cyclotronWorkerPostgres?.stop().then(() => console.log('Stopped cyclotronWorkerPostgres')),- ].filter((s): s is Promise<void> => s !== undefined)-- await Promise.all(stoppers)+ cyclotronWorker?.stop().then(() => console.log('Stopped cyclotronWorker')),+ ])await kafkaProducer.disconnect()await closeHub(hub)mockProducerObserver.resetKafkaProducer()diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 2a51e17d1beb..bdd1bd81bdb6 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -48,9 +48,6 @@ export type CdpConfig = ClickhouseConfig & {DISABLE_OPENTELEMETRY_TRACING: booleanCDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND: CyclotronJobQueueKindCDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: CyclotronJobQueueSource- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING: string- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING: string- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES: booleanCDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: stringCDP_LEGACY_EVENT_CONSUMER_GROUP_ID: string@@ -97,6 +94,9 @@ export type CdpConfig = ClickhouseConfig & {HOG_INVOCATION_RESULTS_PRODUCER: CdpProducerNameHOG_INVOCATION_RESULTS_ENABLED: booleanHOG_INVOCATION_RERUN_MAX_COUNT: number+ // How many rerun wrapper jobs the worker dequeues per cyclotron-v2 poll.+ // Kept small by default — each job runs a full ClickHouse query per page.+ CDP_RERUN_WORKER_BATCH_SIZE: numberCDP_PREFILTERED_EVENTS_TOPIC: stringCDP_PREFILTERED_EVENTS_PRODUCER: CdpProducerNameCDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: string@@ -162,9 +162,6 @@ export function getDefaultCdpConfig(): CdpConfig {DISABLE_OPENTELEMETRY_TRACING: false,CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND: 'hog',CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'kafka',- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING: '*:kafka',- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING: '',- CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES: false,CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '',CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: 'clickhouse-plugin-server-async-onevent',@@ -212,6 +209,9 @@ export function getDefaultCdpConfig(): CdpConfig {// Hard cap on rows a single rerun wrapper job will drain. Mirrors the// Django serializer's HOG_INVOCATION_RERUN_MAX_COUNT (same env var).HOG_INVOCATION_RERUN_MAX_COUNT: 10000,+ // Small by default — rerun jobs are heavy (a full ClickHouse query per+ // page), so a replica drains one wrapper job at a time unless tuned up.+ CDP_RERUN_WORKER_BATCH_SIZE: 1,CDP_PREFILTERED_EVENTS_TOPIC: KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,CDP_PREFILTERED_EVENTS_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.tsindex 073ea130c53b..eb10c5a2337a 100644--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts@@ -1,3 +1,5 @@+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'+import { HogFlow } from '~/schema/hogflow'import { UUIDT } from '~/utils/utils'@@ -8,7 +10,6 @@ import { closeHub, createHub } from '../../utils/db/hub'import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { createKafkaMessage } from '../_tests/fixtures'import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { BatchHogFlowRequest, CdpBatchHogFlowRequestsConsumer } from './cdp-batch-hogflow.consumer'jest.setTimeout(1000)@@ -17,7 +18,7 @@ describe('CdpBatchHogFlowRequestsConsumer', () => {let processor: CdpBatchHogFlowRequestsConsumerlet hub: Hublet team: Team- let mockQueueInvocations: jest.Mock+ let mockQueueInvocations: jest.MockedFunction<any>const insertHogFlow = async (hogFlow: HogFlow) => {const teamId = hogFlow.team_id ?? team.id@@ -35,7 +36,9 @@ describe('CdpBatchHogFlowRequestsConsumer', () => {hub = await createHub()team = await getFirstTeam(hub.postgres)- processor = new CdpBatchHogFlowRequestsConsumer(hub, createCdpConsumerDeps(hub))+ const mockJobQueue = createMockJobQueue()++ processor = new CdpBatchHogFlowRequestsConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic onlyprocessor['kafkaConsumer'] = {@@ -44,13 +47,7 @@ describe('CdpBatchHogFlowRequestsConsumer', () => {isHealthy: jest.fn(),} as any- processor['cyclotronJobQueue'] = {- queueInvocations: jest.fn(),- startAsProducer: jest.fn(() => Promise.resolve()),- stop: jest.fn(),- } as unknown as jest.Mocked<CyclotronJobQueue>-- mockQueueInvocations = jest.mocked(processor['cyclotronJobQueue']['queueInvocations'])+ mockQueueInvocations = mockJobQueue.queueInvocationsawait processor.start()})diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.tsindex 0746c19dae44..866894320771 100644--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts@@ -12,7 +12,7 @@ import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'import { logger, serializeError } from '../../utils/logger'import { UUIDT } from '../../utils/utils'import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionFilters } from '../types'import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals, logEntry } from '../utils'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'@@ -35,18 +35,19 @@ export interface BatchHogFlowRequestMessage {export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServerConfig> {protected name = 'CdpBatchHogFlowRequestsConsumer'- private cyclotronJobQueue: CyclotronJobQueue+ private cyclotronJobQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFlowBatchPersonQueryService: HogFlowBatchPersonQueryServiceconstructor(config: PluginsServerConfig,deps: CdpConsumerBaseDeps,+ jobQueue: JobQueue,topic: string = KAFKA_CDP_BATCH_HOGFLOW_REQUESTS,groupId: string = 'cdp-batch-hogflow-requests-consumer') {super(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.cyclotronJobQueue = jobQueuethis.kafkaConsumer = createKafkaConsumer({ groupId, topic })this.hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(new InternalFetchService(config.INTERNAL_API_BASE_URL, config.INTERNAL_API_SECRET)@@ -354,7 +355,7 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServlogger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()logger.info('💤', 'Stopping cyclotron job queue...')- await this.cyclotronJobQueue.stop()+ await this.cyclotronJobQueue.stopProducer()logger.info('💤', 'Stopping consumer...')// IMPORTANT: super always comes lastawait super.stop()diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.tsindex 5969646e4cbb..12d7858fa987 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts@@ -1,3 +1,5 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'+import { DateTime } from 'luxon'import { HogFlow } from '~/schema/hogflow'@@ -116,10 +118,12 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {new Set(),'test')- const processor = new CdpCyclotronWorkerHogFlow(hub, {- ...createCdpConsumerDeps(hub),- personRepository: personhogRepo,- })+ const mockJobQueue = createMockJobQueue()+ const processor = new CdpCyclotronWorkerHogFlow(+ hub,+ { ...createCdpConsumerDeps(hub), personRepository: personhogRepo },+ mockJobQueue+ )const invocations = [createSerializedHogFlowInvocation(hogFlow, {@@ -164,10 +168,12 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {new Set(),'test')- const processor = new CdpCyclotronWorkerHogFlow(hub, {- ...createCdpConsumerDeps(hub),- personRepository: personhogRepo,- })+ const mockJobQueue2 = createMockJobQueue()+ const processor = new CdpCyclotronWorkerHogFlow(+ hub,+ { ...createCdpConsumerDeps(hub), personRepository: personhogRepo },+ mockJobQueue2+ )const invocations = [createSerializedHogFlowInvocation(hogFlow, {diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex decaadad883b..8a39ce01c89d 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -2,6 +2,7 @@ import { instrumented } from '~/common/tracing/tracing-utils'import { PluginsServerConfig } from '~/types'import { logger } from '../../utils/logger'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '../types'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'import { CdpConsumerBaseDeps } from './cdp-base.consumer'@@ -10,8 +11,8 @@ import { CdpCyclotronWorker } from './cdp-cyclotron-worker.consumer'export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {protected override name = 'CdpCyclotronWorkerHogFlow'- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {- super(config, deps, 'hogflow')+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, jobQueue: JobQueue) {+ super(config, deps, jobQueue, 'hogflow')}@instrumented('cdpConsumer.handleEachBatch.executeInvocations')diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.tsindex d2f18c0aa519..cf4961950401 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts@@ -1,3 +1,5 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'+import { DateTime } from 'luxon'import { HogFlow } from '~/schema/hogflow'@@ -73,7 +75,8 @@ describe('CdpCyclotronWorkerHogFlow', () => {const team2Id = await createTeam(hub.postgres, team.organization_id)team2 = (await getTeam(hub.postgres, team2Id))!- processor = new CdpCyclotronWorkerHogFlow(hub, createCdpConsumerDeps(hub))+ const mockJobQueue = createMockJobQueue()+ processor = new CdpCyclotronWorkerHogFlow(hub, createCdpConsumerDeps(hub), mockJobQueue)hogFlows = []hogFlows.push(diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-plugins.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-plugins.test.tsindex d346581f9482..18425dadaffb 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-plugins.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-plugins.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'import { mockFetch } from '~/tests/helpers/mocks/request.mock'@@ -55,13 +56,9 @@ describe('CdpCyclotronWorkerPlugins', () => {hub = await createHub()team = await getFirstTeam(hub.postgres)- processor = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub))-- await processor.start()-- jest.spyOn(processor['cyclotronJobQueue']!, 'queueInvocationResults').mockImplementation(() =>- Promise.resolve()- )+ const mockJobQueue = createMockJobQueue()+ mockJobQueue.queueInvocationResults.mockResolvedValue(undefined)+ processor = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub), mockJobQueue)const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.tsindex 9121d47690c5..03618e26a8e5 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts@@ -3,7 +3,7 @@ import { instrumented } from '~/common/tracing/tracing-utils'import { HealthCheckResult, PluginsServerConfig } from '../../types'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import {CYCLOTRON_INVOCATION_JOB_QUEUES,CyclotronJobInvocation,@@ -16,16 +16,17 @@ import { mirrorCall } from '../utils/mirror-call'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'/**- * The future of the CDP consumer. This will be the main consumer that will handle all hog jobs from Cyclotron+ * CDP worker that consumes and processes hog function / hogflow jobs.+ * Receives its job queue backend via constructor injection.*/export class CdpCyclotronWorker<TConfig extends PluginsServerConfig = PluginsServerConfig,> extends CdpConsumerBase<TConfig> {protected name = 'CdpCyclotronWorker'- protected cyclotronJobQueue: CyclotronJobQueue+ protected cyclotronJobQueue: JobQueueprotected queue: CyclotronJobQueueKind- constructor(config: TConfig, deps: CdpConsumerBaseDeps, queue?: CyclotronJobQueueKind) {+ constructor(config: TConfig, deps: CdpConsumerBaseDeps, jobQueue: JobQueue, queue?: CyclotronJobQueueKind) {super(config, deps)this.queue = queue ?? config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND@@ -33,7 +34,7 @@ export class CdpCyclotronWorker<throw new Error(`Invalid cyclotron job queue kind: ${this.queue}`)}- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.cyclotronJobQueue = jobQueue}@instrumented({ key: 'cdpConsumer.handleEachBatch.executeInvocations', timeoutMs: 30_000, sendException: false })@@ -173,12 +174,14 @@ export class CdpCyclotronWorker<public override async start() {await super.start()- await this.cyclotronJobQueue.start(this.queue, (batch) => this.processBatch(batch))+ await this.cyclotronJobQueue.startAsProducer()+ await this.cyclotronJobQueue.startAsConsumer(this.queue, (batch) => this.processBatch(batch))}public override async stop() {logger.info('🔄', 'Stopping cyclotron worker consumer')- await this.cyclotronJobQueue.stop()+ await this.cyclotronJobQueue.stopConsumer()+ await this.cyclotronJobQueue.stopProducer()// IMPORTANT: super always comes lastawait super.stop()diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.tsindex 48782013767d..1592d383e2fc 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockFetch } from '~/tests/helpers/mocks/request.mock'import { DateTime } from 'luxon'@@ -38,7 +39,7 @@ describe('CdpCyclotronWorker', () => {await resetTestDatabase()hub = await createHub()team = await getFirstTeam(hub.postgres)- processor = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub))+ processor = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub), createMockJobQueue())fn = await insertHogFunction(hub.postgres,diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.tsindex 6dee9b0e1a9e..9605b33dedcb 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '../../../tests/helpers/mocks/producer.mock'import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'@@ -7,7 +8,6 @@ import { closeHub, createHub } from '../../utils/db/hub'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { insertHogFunction as _insertHogFunction, createKafkaMessage } from '../_tests/fixtures'import { CdpDataWarehouseEvent } from '../schema'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'import { CdpDatawarehouseEventsConsumer } from './cdp-data-warehouse-events.consumer'@@ -19,7 +19,7 @@ describe('CdpDatawarehouseEventsConsumer', () => {let hub: Hublet team: Teamlet team2: Team- let mockQueueInvocations: jest.Mock+ let mockQueueInvocations: jest.MockedFunction<any>const createDataWarehouseEvent = (teamId: number, properties: Record<string, any> = {}): CdpDataWarehouseEvent => {return {@@ -56,7 +56,9 @@ describe('CdpDatawarehouseEventsConsumer', () => {// Set up default quota limiting mock - not limited by defaultjest.spyOn(hub.quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(false)- processor = new CdpDatawarehouseEventsConsumer(hub, createCdpConsumerDeps(hub))+ const mockJobQueue = createMockJobQueue()++ processor = new CdpDatawarehouseEventsConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic onlyprocessor['kafkaConsumer'] = {@@ -65,13 +67,7 @@ describe('CdpDatawarehouseEventsConsumer', () => {isHealthy: jest.fn(() => ({ status: 'healthy' })),} as any- processor['cyclotronJobQueue'] = {- queueInvocations: jest.fn(),- startAsProducer: jest.fn(() => Promise.resolve()),- stop: jest.fn(),- } as unknown as jest.Mocked<CyclotronJobQueue>-- mockQueueInvocations = jest.mocked(processor['cyclotronJobQueue']['queueInvocations'])+ mockQueueInvocations = mockJobQueue.queueInvocationsawait processor.start()})diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex 9103c4aa39f7..eda20cedb8c7 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -10,7 +10,7 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { CdpDataWarehouseEvent, CdpDataWarehouseEventSchema } from '../schema'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'@@ -22,13 +22,13 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {protected name = 'CdpDatawarehouseEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['destination']- protected cyclotronJobQueue: CyclotronJobQueue+ protected hogQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, hogQueue: JobQueue) {super(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = hogQueuethis.kafkaConsumer = createKafkaConsumer({groupId: 'cdp-data-warehouse-events-consumer',topic: 'cdp_data_warehouse_source_table',@@ -63,7 +63,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {return {backgroundTask: Promise.all([instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ this.hogQueue.queueInvocations(invocationsToBeQueued)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -112,7 +112,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {public override async start(): Promise<void> {await super.start()- await this.cyclotronJobQueue.startAsProducer()+ await this.hogQueue.startAsProducer()await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })return await instrumentFn('cdpConsumer.handleEachBatch', async () => {@@ -126,7 +126,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- await this.cyclotronJobQueue.stop()+ await this.hogQueue.stopProducer()await super.stop()}diff --git a/nodejs/src/cdp/consumers/cdp-dwh-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-dwh-source-webhooks.consumer.test.tsindex 5058725d6038..1d049c49b824 100644--- a/nodejs/src/cdp/consumers/cdp-dwh-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-dwh-source-webhooks.consumer.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'import { mockFetch } from '~/tests/helpers/mocks/request.mock'@@ -186,7 +187,10 @@ describe('DWH source webhooks', () => {const signingSecret = 'whsec_testsecret'beforeEach(async () => {- api = new CdpApi(hub, createCdpConsumerDeps(hub))+ api = new CdpApi(hub, createCdpConsumerDeps(hub), {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })app = setupExpressApp()app.use('/', api.router())server = app.listen(0, () => {})diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.tsindex 66549992953b..5222a3651c94 100644--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '../../../tests/helpers/mocks/producer.mock'import { DateTime } from 'luxon'@@ -21,36 +22,27 @@ import {insertHogFunction as _insertHogFunction,createHogExecutionGlobals,createIncomingEvent,- createInternalEvent,createKafkaMessage,} from '../_tests/fixtures'import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'import { CdpEventsConsumer } from './cdp-events.consumer'-import { CdpInternalEventsConsumer } from './cdp-internal-event.consumer'jest.setTimeout(1000)-/**- * NOTE: The internal and normal events consumers are very similar so we can test them together- */-describe.each([- [CdpEventsConsumer.name, CdpEventsConsumer, 'destination' as const],- [CdpInternalEventsConsumer.name, CdpInternalEventsConsumer, 'internal_destination' as const],-])('%s', (_name, Consumer, hogType) => {- let processor: CdpEventsConsumer | CdpInternalEventsConsumer+describe('CdpEventsConsumer', () => {+ let processor: CdpEventsConsumerlet hub: Hublet team: Teamlet team2: Team- let mockQueueInvocations: jest.Mock+ let mockQueueInvocations: jest.MockedFunction<any>const insertHogFunction = async (hogFunction: Partial<HogFunctionType>) => {const teamId = hogFunction.team_id ?? team.idconst item = await _insertHogFunction(hub.postgres, teamId, {...hogFunction,- type: hogType,+ type: 'destination',})// Trigger the reload that django would doprocessor['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [item.id])@@ -70,22 +62,21 @@ describe.each([// Set up default quota limiting mock - not limited by defaultjest.spyOn(hub.quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(false)- processor = new Consumer(hub, createCdpConsumerDeps(hub))+ const mockJobQueue = createMockJobQueue()++ processor = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub), {+ hogQueue: mockJobQueue,+ hogflowQueue: mockJobQueue,+ })// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic only- // `as any` required because `processor` is a union type — TS doesn't expose protected members on unions- ;(processor as any)['kafkaConsumer'] = {+ processor['kafkaConsumer'] = {connect: jest.fn(),disconnect: jest.fn(),isHealthy: jest.fn(),} as any- ;(processor as any)['cyclotronJobQueue'] = {- queueInvocations: jest.fn(),- startAsProducer: jest.fn(() => Promise.resolve()),- stop: jest.fn(),- } as unknown as jest.Mocked<CyclotronJobQueue>- mockQueueInvocations = jest.mocked((processor as any)['cyclotronJobQueue']['queueInvocations'])+ mockQueueInvocations = mockJobQueue.queueInvocationsawait processor.start()})@@ -109,16 +100,10 @@ describe.each([...HOG_FILTERS_EXAMPLES.no_filters,})- const events =- processor instanceof CdpInternalEventsConsumer- ? [- createKafkaMessage(createInternalEvent(team.id, {})),- createKafkaMessage(createInternalEvent(team2.id, {})),- ]- : [- createKafkaMessage(createIncomingEvent(team.id, {})),- createKafkaMessage(createIncomingEvent(team2.id, {})),- ]+ const events = [+ createKafkaMessage(createIncomingEvent(team.id, {})),+ createKafkaMessage(createIncomingEvent(team2.id, {})),+ ]const invocations = await processor._parseKafkaBatch(events)expect(invocations).toHaveLength(1)expect(invocations[0].project.id).toBe(team.id)@@ -231,7 +216,7 @@ describe.each([)// Billing is per-event, not per-destination: 1 event → 2 destinations = 1 billable_invocation- if (hogType === 'destination') {+ {const billingMetrics = metrics.filter((m: any) => m.value.metric_name === 'billable_invocation')expect(billingMetrics).toHaveLength(1)expect(billingMetrics[0].value).toMatchObject({@@ -287,24 +272,20 @@ describe.each([},},// Billing is per-event: 1 event → 1 destination = 1 billable_invocation- ...(hogType !== 'destination'- ? []- : [- {- key: null,- topic: 'clickhouse_app_metrics2_test',- value: {- app_source: 'hog_function',- app_source_id: '_event_trigger',- instance_id: globals.event.uuid,- count: 1,- metric_kind: 'billing',- metric_name: 'billable_invocation',- team_id: 2,- timestamp: expect.any(String),- },- },- ]),+ {+ key: null,+ topic: 'clickhouse_app_metrics2_test',+ value: {+ app_source: 'hog_function',+ app_source_id: '_event_trigger',+ instance_id: globals.event.uuid,+ count: 1,+ metric_kind: 'billing',+ metric_name: 'billable_invocation',+ team_id: 2,+ timestamp: expect.any(String),+ },+ },])})@@ -343,7 +324,7 @@ describe.each([])})- if (hogType === 'destination') {+ {it('should bill once per event, not per destination (multiple events)', async () => {// Create a second event with different UUIDconst globals2 = createHogExecutionGlobals({@@ -570,7 +551,7 @@ describe.each([})describe('hog flow processing', () => {- let processor: CdpEventsConsumer | CdpInternalEventsConsumer+ let processor: CdpEventsConsumerlet hub: Hublet team: Team@@ -587,7 +568,12 @@ describe('hog flow processing', () => {await resetTestDatabase()hub = await createHub()team = await getFirstTeam(hub.postgres)- processor = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub))+ const mockQueue = createMockJobQueue()++ processor = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub), {+ hogQueue: mockQueue,+ hogflowQueue: mockQueue,+ })// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic onlyprocessor['kafkaConsumer'] = {@@ -595,11 +581,6 @@ describe('hog flow processing', () => {disconnect: jest.fn(),isHealthy: jest.fn(),} as any- processor['cyclotronJobQueue'] = {- queueInvocations: jest.fn(),- startAsProducer: jest.fn(() => Promise.resolve()),- stop: jest.fn(),- } as unknown as jest.Mocked<CyclotronJobQueue>await processor.start()})diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex d8e4ea341bf5..f18b7c2e4344 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -11,7 +11,7 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'@@ -21,7 +21,8 @@ export class CdpEventsConsumer<> extends CdpConsumerBase<TConfig> {protected name = 'CdpEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['destination']- private cyclotronJobQueue: CyclotronJobQueue+ protected hogQueue: JobQueue+ protected hogflowQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline@@ -30,11 +31,13 @@ export class CdpEventsConsumer<constructor(config: TConfig,deps: CdpConsumerBaseDeps,+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue },topic: string = KAFKA_EVENTS_JSON,groupId: string = 'cdp-processed-events-consumer') {super(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = jobQueues.hogQueue+ this.hogflowQueue = jobQueues.hogflowQueuethis.kafkaConsumer = createKafkaConsumer({ groupId, topic })this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {hogFunctionManager: this.hogFunctionManager,@@ -94,8 +97,11 @@ export class CdpEventsConsumer<return {// This is all IO so we can set them off in the background and start processing the next batchbackgroundTask: Promise.all([- instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ instrumentFn({ key: 'cdp.background_task.queue_hog_invocations', sendException: false }, () =>+ this.hogQueue.queueInvocations(hogInvocations)+ ),+ instrumentFn({ key: 'cdp.background_task.queue_hogflow_invocations', sendException: false }, () =>+ this.hogflowQueue.queueInvocations(hogflowInvocations)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -109,7 +115,7 @@ export class CdpEventsConsumer<this.invocationResultsService.invocationResultsRowsService.flush()),]),- invocations: invocationsToBeQueued,+ invocations: [...hogInvocations, ...hogflowInvocations],}}@@ -145,8 +151,7 @@ export class CdpEventsConsumer<public override async start(): Promise<void> {await super.start()- // Make sure we are ready to produce to cyclotron first- await this.cyclotronJobQueue.startAsProducer()+ await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])// Start consuming messagesawait this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, {@@ -165,9 +170,8 @@ export class CdpEventsConsumer<public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- logger.info('💤', 'Stopping cyclotron job queue...')- await this.cyclotronJobQueue.stop()- logger.info('💤', 'Stopping consumer...')+ logger.info('💤', 'Stopping job queues...')+ await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])// IMPORTANT: super always comes lastawait super.stop()logger.info('💤', 'Consumer stopped!')diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex 926b5ee32074..207b71b3f2aa 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -10,7 +10,7 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { CdpInternalEventSchema } from '../schema'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { convertInternalEventToHogFunctionInvocationGlobals } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'@@ -20,13 +20,13 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {protected name = 'CdpInternalEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['internal_destination']- protected cyclotronJobQueue: CyclotronJobQueue+ protected hogQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, hogQueue: JobQueue) {super(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = hogQueuethis.kafkaConsumer = createKafkaConsumer({groupId: 'cdp-internal-events-consumer',topic: KAFKA_CDP_INTERNAL_EVENTS,@@ -61,7 +61,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {return {backgroundTask: Promise.all([instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ this.hogQueue.queueInvocations(invocationsToBeQueued)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -107,7 +107,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {public override async start(): Promise<void> {await super.start()- await this.cyclotronJobQueue.startAsProducer()+ await this.hogQueue.startAsProducer()await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })return await instrumentFn('cdpConsumer.handleEachBatch', async () => {@@ -121,7 +121,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- await this.cyclotronJobQueue.stop()+ await this.hogQueue.stopProducer()await super.stop()}diff --git a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.tsindex 00b073129a07..0cad99f7fa8b 100644--- a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts@@ -1,11 +1,13 @@+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import '../../../tests/helpers/mocks/producer.mock'import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'-import { getFirstTeam, resetTestDatabase } from '../../../tests/helpers/sql'+import { createOrganization, createTeam, getFirstTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'import { Hub, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { insertHogFunction as _insertHogFunction, createInternalEvent, createKafkaMessage } from '../_tests/fixtures'+import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import { HogFunctionType } from '../types'import { CdpInternalEventsConsumer } from './cdp-internal-event.consumer'@@ -13,11 +15,17 @@ describe('CDP Internal Events Consumer', () => {let processor: CdpInternalEventsConsumerlet hub: Hublet team: Team+ let team2: Team+ let mockQueueInvocations: jest.MockedFunction<any>const insertHogFunction = async (hogFunction: Partial<HogFunctionType>) => {- const item = await _insertHogFunction(hub.postgres, team.id, hogFunction)+ const teamId = hogFunction.team_id ?? team.id+ const item = await _insertHogFunction(hub.postgres, teamId, {+ ...hogFunction,+ type: 'internal_destination',+ })// Trigger the reload that django would do- processor['hogFunctionManager']['onHogFunctionsReloaded'](team.id, [item.id])+ processor['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [item.id])return item}@@ -28,7 +36,24 @@ describe('CDP Internal Events Consumer', () => {})team = await getFirstTeam(hub.postgres)- processor = new CdpInternalEventsConsumer(hub, createCdpConsumerDeps(hub))+ const otherOrganizationId = await createOrganization(hub.postgres)+ const team2Id = await createTeam(hub.postgres, otherOrganizationId)+ team2 = (await getTeam(hub.postgres, team2Id))!++ jest.spyOn(hub.quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(false)++ const mockJobQueue = createMockJobQueue()+ processor = new CdpInternalEventsConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)++ // Don't actually connect Kafka — test the core logic only+ processor['kafkaConsumer'] = {+ connect: jest.fn(),+ disconnect: jest.fn(),+ isHealthy: jest.fn(),+ } as any++ mockQueueInvocations = mockJobQueue.queueInvocations+await processor.start()})@@ -41,7 +66,7 @@ describe('CDP Internal Events Consumer', () => {jest.useRealTimers()})- describe('_handleKafkaBatch', () => {+ describe('_parseKafkaBatch', () => {it('should ignore invalid message', async () => {const events = await processor._parseKafkaBatch([createKafkaMessage({})])expect(events).toHaveLength(0)@@ -58,7 +83,6 @@ describe('CDP Internal Events Consumer', () => {...HOG_EXAMPLES.simple_fetch,...HOG_INPUTS_EXAMPLES.simple_fetch,...HOG_FILTERS_EXAMPLES.no_filters,- type: 'internal_destination',})})@@ -101,4 +125,100 @@ describe('CDP Internal Events Consumer', () => {})})})++ describe('team filtering', () => {+ it('should not parse events for teams without hog functions', async () => {+ await insertHogFunction({+ team_id: team.id,+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const events = [+ createKafkaMessage(createInternalEvent(team.id, {})),+ createKafkaMessage(createInternalEvent(team2.id, {})),+ ]++ const invocations = await processor._parseKafkaBatch(events)+ expect(invocations).toHaveLength(1)+ expect(invocations[0].project.id).toBe(team.id)++ await insertHogFunction({+ team_id: team2.id,+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const invocations2 = await processor._parseKafkaBatch(events)+ expect(invocations2).toHaveLength(2)+ })+ })++ describe('processBatch', () => {+ it('should build invocations from internal events and queue them', async () => {+ const fn = await insertHogFunction({+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const messages = [createKafkaMessage(createInternalEvent(team.id, {}))]+ const globals = await processor._parseKafkaBatch(messages)+ const { invocations, backgroundTask } = await processor.processBatch(globals)+ await backgroundTask++ expect(invocations).toHaveLength(1)+ expect(invocations[0].functionId).toBe(fn.id)+ expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)+ })++ it('should return empty when given no events', async () => {+ const { invocations, backgroundTask } = await processor.processBatch([])+ await backgroundTask++ expect(invocations).toHaveLength(0)+ expect(mockQueueInvocations).not.toHaveBeenCalled()+ })++ it('should filter out functions that are disabled', async () => {+ const fn = await insertHogFunction({+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })+ await processor.hogWatcher.forceStateChange(fn, HogWatcherState.disabled)++ const messages = [createKafkaMessage(createInternalEvent(team.id, {}))]+ const globals = await processor._parseKafkaBatch(messages)+ const { invocations } = await processor.processBatch(globals)++ expect(invocations).toHaveLength(0)+ })++ it('should only load internal_destination hog functions (filters out destination type)', async () => {+ // Insert a `destination` type function for the same team+ await _insertHogFunction(hub.postgres, team.id, {+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ type: 'destination',+ })++ // Insert an internal_destination function — should be the only one picked up+ const internalFn = await insertHogFunction({+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const messages = [createKafkaMessage(createInternalEvent(team.id, {}))]+ const globals = await processor._parseKafkaBatch(messages)+ const { invocations } = await processor.processBatch(globals)++ expect(invocations).toHaveLength(1)+ expect(invocations[0].functionId).toBe(internalFn.id)+ })+ })})diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.tsindex 74c6effff251..c42505a560a2 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import '../../../tests/helpers/mocks/producer.mock'import { forSnapshot } from '~/tests/helpers/snapshots'@@ -36,7 +37,8 @@ describe('CDP Person Updates Consumer', () => {})team = await getFirstTeam(hub.postgres)- processor = new CdpPersonUpdatesConsumer(hub, createCdpConsumerDeps(hub))+ const mockJobQueue = createMockJobQueue()+ processor = new CdpPersonUpdatesConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)await processor.start()hogFunction = createHogFunction({diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.tsindex e181d22c70ce..79418d413451 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts@@ -10,7 +10,7 @@ import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, CyclotronPerson, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { getPersonDisplayName } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'@@ -20,13 +20,13 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {protected name = 'CdpPersonUpdatesConsumer'protected hogTypes: HogFunctionTypeType[] = ['destination']- protected cyclotronJobQueue: CyclotronJobQueue+ protected hogQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, hogQueue: JobQueue) {super(config, deps)- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = hogQueuethis.kafkaConsumer = createKafkaConsumer({groupId: 'cdp-person-updates-consumer',topic: KAFKA_PERSON,@@ -61,7 +61,7 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {return {backgroundTask: Promise.all([instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued)+ this.hogQueue.queueInvocations(invocationsToBeQueued)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -110,7 +110,7 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {public override async start(): Promise<void> {await super.start()- await this.cyclotronJobQueue.startAsProducer()+ await this.hogQueue.startAsProducer()await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })return await instrumentFn('cdpConsumer.handleEachBatch', async () => {@@ -124,7 +124,7 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- await this.cyclotronJobQueue.stop()+ await this.hogQueue.stopProducer()await super.stop()}diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.tsindex 5e5a5c65e8c6..4cc0659b9e79 100644--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts@@ -6,10 +6,22 @@ import { Hub } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'import { parseJSON } from '../../utils/json-parse'import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'+import { RerunJobQueues } from '../rerun/rerun-paginator.service'import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { CdpRerunWorkerConsumer } from './cdp-rerun-worker.consumer'+// Minimal stub for a job queue backend — the consumer only calls the producer+// lifecycle hooks; the paginator (which would call queueInvocations) is stubbed.+const buildMockJobQueues = (): RerunJobQueues => {+ const stub = () =>+ ({+ startAsProducer: jest.fn().mockResolvedValue(undefined),+ stopProducer: jest.fn().mockResolvedValue(undefined),+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ }) as any+ return { hog_function: stub(), hog_flow: stub() }+}+jest.setTimeout(20000)const buildDequeuedJob = (overrides: Partial<CyclotronV2DequeuedJob> = {}): jest.Mocked<CyclotronV2DequeuedJob> => {@@ -64,7 +76,7 @@ describe('CdpRerunWorkerConsumer', () => {// consumer constructs cleanly. Real queue interactions are mocked below.hub.CYCLOTRON_NODE_DATABASE_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'- consumer = new CdpRerunWorkerConsumer(hub, createCdpConsumerDeps(hub))+ consumer = new CdpRerunWorkerConsumer(hub, createCdpConsumerDeps(hub), buildMockJobQueues())// Replace the paginator with a stub so we exercise the consumer's// ack/reschedule/fail decisions without hitting ClickHouse. The catch@@ -75,13 +87,9 @@ describe('CdpRerunWorkerConsumer', () => {writeWrapperFailure: jest.fn().mockResolvedValue(undefined),} as any- // We don't want the consumer to actually start the cyclotron worker loop or- // the cyclotronJobQueue producer plumbing during these tests.+ // Don't start the real cyclotron worker loop — job queue producers are+ // already stubbed via buildMockJobQueues.consumer['worker'] = null- consumer['cyclotronJobQueue'] = {- startAsProducer: jest.fn(() => Promise.resolve()),- stop: jest.fn(() => Promise.resolve()),- } as unknown as jest.Mocked<CyclotronJobQueue>})afterEach(async () => {diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.tsindex e9cba6e0d847..6672255aae44 100644--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts@@ -7,10 +7,9 @@ import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'-import { RerunPaginatorService } from '../rerun/rerun-paginator.service'+import { RerunJobQueues, RerunPaginatorService } from '../rerun/rerun-paginator.service'import { CyclotronV2Worker } from '../services/cyclotron-v2'import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'// Heartbeat interval — the cyclotron-v2 lock timeout is 30s by default, send@@ -45,14 +44,15 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>protected name = 'CdpRerunWorkerConsumer'private worker: CyclotronV2Worker | null = null- private cyclotronJobQueue: CyclotronJobQueue+ private jobQueues: RerunJobQueuesprivate paginator: RerunPaginatorService | null = nullprivate clickhouseClient: ClickHouseClient | null = null- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, jobQueues: RerunJobQueues) {super(config, deps)- // Used by the paginator to re-enqueue invocations as it pages.- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ // Used by the paginator to re-enqueue rehydrated invocations as it+ // pages — hog functions to kafka, hog flows to postgres-v2.+ this.jobQueues = jobQueues}override async start(): Promise<void> {@@ -60,7 +60,8 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>throw new Error('CYCLOTRON_NODE_DATABASE_URL is required for the rerun worker')}- await this.cyclotronJobQueue.startAsProducer()+ await this.jobQueues.hog_function.startAsProducer()+ await this.jobQueues.hog_flow.startAsProducer()// Dedicated ClickHouse client for the paginator. The cluster's certs// are issued for an internal hostname that doesn't match the one we@@ -99,7 +100,7 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>// config, since we strip `inputs` from the persisted globals.this.hogInputsService,this.invocationResultsService.invocationResultsRowsService,- this.cyclotronJobQueue,+ this.jobQueues,this.invocationResultsService.monitoringService,this.config.HOG_INVOCATION_RERUN_MAX_COUNT)@@ -107,10 +108,11 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>this.worker = new CyclotronV2Worker({pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL },queueName: RERUN_QUEUE_NAME,- // Rerun jobs are heavy (each runs a full ClickHouse query) — pull- // them one at a time so a single replica can be deployed at high- // concurrency without overwhelming ClickHouse.- batchMaxSize: 1,+ // Rerun jobs are heavy (each runs a full ClickHouse query) — the+ // default of 1 pulls them one at a time so a single replica can be+ // deployed at high concurrency without overwhelming ClickHouse.+ // Tunable via CDP_RERUN_WORKER_BATCH_SIZE.+ batchMaxSize: this.config.CDP_RERUN_WORKER_BATCH_SIZE,pollDelayMs: 1000,})@@ -122,7 +124,8 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>override async stop(): Promise<void> {this.isStopping = trueawait this.worker?.disconnect()- await this.cyclotronJobQueue.stop()+ await this.jobQueues.hog_function.stopProducer()+ await this.jobQueues.hog_flow.stopProducer()await this.clickhouseClient?.close()await this.invocationResultsService.flush()}@@ -146,8 +149,8 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>}private async handleBatch(jobs: CyclotronV2DequeuedJob[]): Promise<void> {- // batchMaxSize=1, so this is effectively one job at a time. The loop- // exists for symmetry with other consumer base classes.+ // Usually one job at a time (CDP_RERUN_WORKER_BATCH_SIZE defaults to 1),+ // but the loop handles a larger batch if the env is tuned up.for (const job of jobs) {await this.handleJob(job)}diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.tsindex a21c866536b5..a65705e90d65 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'import { mockFetch, mockInternalFetch } from '~/tests/helpers/mocks/request.mock'@@ -111,13 +112,18 @@ describe('SourceWebhooksConsumer', () => {let mockExecuteSpy: jest.SpyInstancelet mockQueueInvocationsSpy: jest.SpyInstance+ let mockQueueHogflowInvocationsSpy: jest.SpyInstancebeforeEach(async () => {hub.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS = 50- api = new CdpApi(hub, createCdpConsumerDeps(hub))+ api = new CdpApi(hub, createCdpConsumerDeps(hub), {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })mockExecuteSpy = jest.spyOn(api['cdpSourceWebhooksConsumer']['hogExecutor'], 'execute')- mockQueueInvocationsSpy = jest.spyOn(- api['cdpSourceWebhooksConsumer']['cyclotronJobQueue'],+ mockQueueInvocationsSpy = jest.spyOn(api['cdpSourceWebhooksConsumer']['hogQueue'], 'queueInvocations')+ mockQueueHogflowInvocationsSpy = jest.spyOn(+ api['cdpSourceWebhooksConsumer']['hogflowQueue'],'queueInvocations')app = setupExpressApp()@@ -475,8 +481,8 @@ describe('SourceWebhooksConsumer', () => {status: 'queued',})expect(mockExecuteSpy).toHaveBeenCalledTimes(1)- expect(mockQueueInvocationsSpy).toHaveBeenCalledTimes(1)- const call = mockQueueInvocationsSpy.mock.calls[0][0][0]+ expect(mockQueueHogflowInvocationsSpy).toHaveBeenCalledTimes(1)+ const call = mockQueueHogflowInvocationsSpy.mock.calls[0][0][0]expect(call.queue).toEqual('hogflow')expect(call.hogFlow).toMatchObject(hogFlow)})@@ -530,9 +536,9 @@ describe('SourceWebhooksConsumer', () => {// (this is what actually captures the event)expect(mockQueueInvocationResults).not.toHaveBeenCalled()- // Verify the workflow invocation was queued- expect(mockQueueInvocationsSpy).toHaveBeenCalledTimes(1)- const invocation = mockQueueInvocationsSpy.mock.calls[0][0][0]+ // Verify the workflow invocation was queued to hogflowQueue+ expect(mockQueueHogflowInvocationsSpy).toHaveBeenCalledTimes(1)+ const invocation = mockQueueHogflowInvocationsSpy.mock.calls[0][0][0]expect(invocation.state.event).toMatchObject({event: 'my-event',diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.tsindex 5e9cc26d48ed..de88cc8f29a5 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts@@ -10,7 +10,7 @@ import { PromiseScheduler } from '../../utils/promise-scheduler'import { UUID, UUIDT } from '../../utils/utils'import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'import { actionIdForLogging } from '../services/hogflows/hogflow-utils'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { HogWatcherFunctionState, HogWatcherState } from '../services/monitoring/hog-watcher.service'import {CyclotronJobInvocationHogFunction,@@ -84,13 +84,19 @@ export class SourceWebhookError extends Error {export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfig> {protected name = 'CdpSourceWebhooksConsumer'- private cyclotronJobQueue: CyclotronJobQueue+ private hogQueue: JobQueue+ private hogflowQueue: JobQueueprivate promiseScheduler: PromiseScheduler- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ constructor(+ config: PluginsServerConfig,+ deps: CdpConsumerBaseDeps,+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }+ ) {super(config, deps)this.promiseScheduler = new PromiseScheduler()- this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ this.hogQueue = jobQueues.hogQueue+ this.hogflowQueue = jobQueues.hogflowQueue}public async getWebhook(webhookId: string): Promise<{ hogFlow?: HogFlow; hogFunction: HogFunctionType } | null> {@@ -295,7 +301,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfcount: 1,})- await this.cyclotronJobQueue.queueInvocations([hogFlowInvocation])+ await this.hogflowQueue.queueInvocations([hogFlowInvocation])} else {addMetric({metric_kind: 'failure',@@ -344,7 +350,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfif (hogFunctionState?.state === HogWatcherState.degraded) {// Degraded functions are not executed immediatelyinvocation.queue = 'hogoverflow'- await this.cyclotronJobQueue.queueInvocations([invocation])+ await this.hogQueue.queueInvocations([invocation])result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation,@@ -374,7 +380,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf// Queue any queued work here. This allows us to enable delayed work like fetching eventually without blocking the API.if (!result.finished) {- await this.cyclotronJobQueue.queueInvocationResults([result])+ await this.hogQueue.queueInvocationResults([result])}const customHttpResponse = getCustomHttpResponse(result)@@ -464,11 +470,11 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfpublic override async start(): Promise<void> {await super.start()// Make sure we are ready to produce to cyclotron first- await this.cyclotronJobQueue.startAsProducer()+ await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])}public override async stop(): Promise<void> {- await this.cyclotronJobQueue.stop()+ await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])await this.promiseScheduler.waitForAllSettled()// IMPORTANT: super always comes lastawait super.stop()diff --git a/nodejs/src/cdp/rerun/rerun-e2e.test.ts b/nodejs/src/cdp/rerun/rerun-e2e.test.tsindex 5e4a505ef308..98c5758b53aa 100644--- a/nodejs/src/cdp/rerun/rerun-e2e.test.ts+++ b/nodejs/src/cdp/rerun/rerun-e2e.test.ts@@ -21,6 +21,8 @@ import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } frimport { CdpCyclotronWorker } from '../consumers/cdp-cyclotron-worker.consumer'import { CdpEventsConsumer } from '../consumers/cdp-events.consumer'import { CdpRerunWorkerConsumer } from '../consumers/cdp-rerun-worker.consumer'+import { CyclotronJobQueueKafka } from '../services/job-queue/job-queue-kafka'+import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'import { compileHog } from '../templates/compiler'import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'import { RerunJobManager } from './rerun-job.manager'@@ -124,6 +126,8 @@ describe('CDP hog invocation rerun e2e', () => {let cyclotronWorker: CdpCyclotronWorkerlet rerunManager: RerunJobManagerlet rerunWorker: CdpRerunWorkerConsumer+ let kafkaQueue: CyclotronJobQueueKafka+ let postgresV2Queue: CyclotronJobQueuePostgresV2let nodeAssertPool: Poollet clickhouse: Clickhouse@@ -163,10 +167,6 @@ describe('CDP hog invocation rerun e2e', () => {hub.CYCLOTRON_DATABASE_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron'hub.CYCLOTRON_NODE_DATABASE_URL = NODE_DB_URLhub.HOG_INVOCATION_RESULTS_ENABLED = true- // Route via cyclotron-v2 so the rerun path exercises the ON CONFLICT- // upsert (rerun re-enqueue uses the original invocation_id, which- // would otherwise collide on the cyclotron_jobs PK).- hub.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = '*:postgres-v2'// Clean any stale rerun wrapper jobs from prior runs.nodeAssertPool = new Pool({ connectionString: NODE_DB_URL })@@ -190,9 +190,13 @@ describe('CDP hog invocation rerun e2e', () => {...HOG_FILTERS_EXAMPLES.no_filters,})- const cyclotronConfig = { ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres-v2' as const }+ kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub)+ postgresV2Queue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)- eventsConsumer = new CdpEventsConsumer(cyclotronConfig, createCdpConsumerDeps(hub, kafkaProducer))+ eventsConsumer = new CdpEventsConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })// We call processBatch directly — no need to actually join the kafka group.// Stubbing keeps the test off Redpanda's stale-group-protocol coordinator,// which otherwise fails the join with "Inconsistent group protocol".@@ -203,7 +207,7 @@ describe('CDP hog invocation rerun e2e', () => {} as anyawait eventsConsumer.start()- cyclotronWorker = new CdpCyclotronWorker(cyclotronConfig, createCdpConsumerDeps(hub, kafkaProducer))+ cyclotronWorker = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub, kafkaProducer), kafkaQueue)await cyclotronWorker.start()rerunManager = new RerunJobManager({ dbUrl: NODE_DB_URL, maxCount: 10000 })@@ -295,7 +299,8 @@ describe('CDP hog invocation rerun e2e', () => {// ── 3. Rerun worker drains the wrapper job ────────────────────────────────rerunWorker = new CdpRerunWorkerConsumer({ ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres' },- createCdpConsumerDeps(hub, kafkaProducer)+ createCdpConsumerDeps(hub, kafkaProducer),+ { hog_function: kafkaQueue, hog_flow: postgresV2Queue })await rerunWorker.start()diff --git a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.tsnew file mode 100644index 000000000000..1aa2cc65ba5c--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts@@ -0,0 +1,115 @@+import { DateTime } from 'luxon'++import { CyclotronJobConflictError } from '../services/cyclotron-v2'+import { HogInputsService } from '../services/hog-inputs.service'+import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'+import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'+import { JobQueue } from '../services/job-queue/job-queue.interface'+import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'+import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'+import { RerunFunctionKind, RerunJobState } from './rerun-job.types'+import { RerunPaginatorService } from './rerun-paginator.service'++/**+ * Unit tests for the paginator's re-enqueue routing. A rerun job is scoped to+ * one function kind, so a whole page routes to one backend — hog functions to+ * kafka, hog flows to postgres-v2, the same split cdp-events-consumer uses.+ *+ * ClickHouse + rehydration are stubbed (private `fetchPage` / `rehydrateBatch`)+ * so these run without infra; the real CH paths are covered by+ * `rerun-paginator.service.test.ts`.+ */+describe('RerunPaginatorService queue routing', () => {+ let hogQueue: jest.Mocked<JobQueue>+ let hogflowQueue: jest.Mocked<CyclotronJobQueuePostgresV2>+ let paginator: RerunPaginatorService++ beforeEach(() => {+ hogQueue = {+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<JobQueue>+ hogflowQueue = {+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<CyclotronJobQueuePostgresV2>++ const invocationResultsRowsService = {+ queueLifecycleRow: jest.fn(),+ queueRerunWrapperRow: jest.fn(),+ dropQueuedRowsFor: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<HogInvocationResultsService>++ const monitoringService = {+ queueLogs: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<HogFunctionMonitoringService>++ paginator = new RerunPaginatorService(+ {} as any,+ {} as unknown as HogFunctionManagerService,+ {} as unknown as HogFlowManagerService,+ {} as unknown as HogInputsService,+ invocationResultsRowsService,+ { hog_function: hogQueue, hog_flow: hogflowQueue },+ monitoringService,+ 10000+ )+ })++ const buildState = (kind: RerunFunctionKind): RerunJobState => ({+ function_kind: kind,+ function_id: kind === 'hog_flow' ? 'flow-1' : 'fn-1',+ request: { filter: { window_start: '2026-01-01T00:00:00Z', window_end: '2027-01-01T00:00:00Z' } },+ progress: { queued: 0, skipped: 0, done: false },+ })++ // Stub the CH query + rehydration so the test exercises only the routing.+ const stubPage = (ids: string[]): void => {+ jest.spyOn(paginator as any, 'fetchPage').mockResolvedValue([])+ jest.spyOn(paginator as any, 'rehydrateBatch').mockResolvedValue({+ queued: ids.length,+ skipped: 0,+ queuedInvocations: ids.map((id) => ({ id })),+ })+ }++ const runPage = (state: RerunJobState) =>+ paginator.processPage(1, state, { jobId: 'test-rerun-job', createdAt: DateTime.now() })++ it('routes hog_function reruns to the kafka (hog) queue, not the hogflow queue', async () => {+ stubPage(['inv-1', 'inv-2'])++ await runPage(buildState('hog_function'))++ expect(hogQueue.queueInvocations).toHaveBeenCalledTimes(1)+ expect((hogQueue.queueInvocations.mock.calls[0][0] as any[]).map((i) => i.id)).toEqual(['inv-1', 'inv-2'])+ expect(hogflowQueue.queueInvocations).not.toHaveBeenCalled()+ })++ it('routes hog_flow reruns to the postgres-v2 (hogflow) queue with overwriteExisting', async () => {+ stubPage(['inv-1', 'inv-2'])++ await runPage(buildState('hog_flow'))++ expect(hogflowQueue.queueInvocations).toHaveBeenCalledTimes(1)+ expect((hogflowQueue.queueInvocations.mock.calls[0][0] as any[]).map((i) => i.id)).toEqual(['inv-1', 'inv-2'])+ // postgres-v2 re-enqueue re-uses the original invocation_id, so it must+ // upsert over the prior terminal row.+ expect(hogflowQueue.queueInvocations.mock.calls[0][1]).toEqual({ overwriteExisting: true })+ expect(hogQueue.queueInvocations).not.toHaveBeenCalled()+ })++ it('counts hogflow in-flight conflicts as skipped instead of failing the page', async () => {+ stubPage(['inv-conflict'])+ // The postgres-v2 upsert raises a conflict when the existing row is+ // still active — the paginator logs + counts it as a skip, not a failure.+ hogflowQueue.queueInvocations.mockRejectedValueOnce(new CyclotronJobConflictError('inv-conflict'))++ const { state: next } = await runPage(buildState('hog_flow'))++ expect(next.progress.queued).toBe(0)+ expect(next.progress.skipped).toBe(1)+ expect(next.progress.last_error).toBeUndefined()+ })+})diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.tsindex 69e2329ae2f3..067dd4b42b69 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts@@ -18,7 +18,8 @@ import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } frimport { createCdpOutputsRegistry } from '../outputs/registry'import { HogInputsService } from '../services/hog-inputs.service'import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'@@ -52,7 +53,9 @@ describe('RerunPaginatorService integration', () => {let seedingService: HogInvocationResultsServicelet chClient: ClickHouseClientlet paginator: RerunPaginatorService- let cyclotronJobQueue: jest.Mocked<CyclotronJobQueue>+ // hog functions re-enqueue to the kafka queue, hog flows to postgres-v2.+ let hogQueue: jest.Mocked<JobQueue>+ let hogflowQueue: jest.Mocked<CyclotronJobQueuePostgresV2>let paginatorLifecycleService: jest.Mocked<HogInvocationResultsService>let paginatorMonitoringService: jest.Mocked<HogFunctionMonitoringService>let hogFunctionManager: HogFunctionManagerService@@ -176,9 +179,12 @@ describe('RerunPaginatorService integration', () => {.mockImplementation((_fn, globals) => Promise.resolve({ ...globals, inputs: { resolved: true } })),} as unknown as jest.Mocked<HogInputsService>- cyclotronJobQueue = {+ hogQueue = {queueInvocations: jest.fn().mockResolvedValue(undefined),- } as unknown as jest.Mocked<CyclotronJobQueue>+ } as unknown as jest.Mocked<JobQueue>+ hogflowQueue = {+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<CyclotronJobQueuePostgresV2>// The paginator's lifecycle service is mocked so we can assert what it// got asked to write (the 'running' row for each rerun). The actual@@ -202,7 +208,7 @@ describe('RerunPaginatorService integration', () => {hogFlowManager,hogInputsService,paginatorLifecycleService,- cyclotronJobQueue,+ { hog_function: hogQueue, hog_flow: hogflowQueue },paginatorMonitoringService,10000)@@ -246,8 +252,8 @@ describe('RerunPaginatorService integration', () => {createdAt: DateTime.now(),})- expect(cyclotronJobQueue.queueInvocations).toHaveBeenCalledTimes(1)- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ expect(hogQueue.queueInvocations).toHaveBeenCalledTimes(1)+ const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]const enqueuedIds = enqueued.map((i) => i.id).sort()expect(enqueuedIds).toEqual(['inv-a', 'inv-c'])@@ -286,7 +292,7 @@ describe('RerunPaginatorService integration', () => {createdAt: DateTime.now(),})- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]expect(enqueued.map((i) => i.id)).toEqual(['inv-real'])// by-ids mode marks done once remaining_ids is drained, regardless of// whether every id had a matching CH row.@@ -314,7 +320,7 @@ describe('RerunPaginatorService integration', () => {// The persisted globals were stripped of `inputs` before storage.expect(persistedGlobals).not.toHaveProperty('inputs')- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]expect((enqueued[0].state.globals as any).inputs).toEqual({ resolved: true })})})@@ -338,7 +344,7 @@ describe('RerunPaginatorService integration', () => {createdAt: DateTime.now(),})- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]const ids = enqueued.map((i) => i.id).sort()expect(ids).toEqual(['fail-1', 'fail-2'])expect(next.progress.queued).toBe(2)@@ -364,7 +370,7 @@ describe('RerunPaginatorService integration', () => {jobId: 'test-rerun-job',createdAt: DateTime.now(),})- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0]?.[0] as+ const enqueued = hogQueue.queueInvocations.mock.calls[0]?.[0] as| CyclotronJobInvocationHogFunction[]| undefinedexpect(enqueued?.map((i) => i.id)).toEqual(['inv-500'])@@ -411,7 +417,7 @@ describe('RerunPaginatorService integration', () => {})expect(next.progress.queued).toBe(0)expect(next.progress.done).toBe(true)- expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()+ expect(hogQueue.queueInvocations).not.toHaveBeenCalled()})})@@ -459,39 +465,7 @@ describe('RerunPaginatorService integration', () => {})expect(next.progress.queued).toBe(0)expect(next.progress.skipped).toBe(1)- expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()- })- })-- describe('conflict handling', () => {- it('counts in-flight invocations as skipped instead of failing the page', async () => {- await seedRows([{ invocation_id: 'inv-conflict', status: 'failed', error: new Error('5xx') }])-- // Simulate the v2 queue raising a conflict for our re-enqueue —- // we want the paginator to log + count it as a skip, not blow up- // the page. Use the same re-export the paginator imports from so- // `instanceof` matches.- const { CyclotronJobConflictError } = await import('../services/cyclotron-v2/index.js')- cyclotronJobQueue.queueInvocations.mockRejectedValueOnce(new CyclotronJobConflictError('inv-conflict'))-- const state = buildState({- request: {- filter: {- window_start: '2026-01-01T00:00:00Z',- window_end: '2027-01-01T00:00:00Z',- invocation_ids: ['inv-conflict'],- },- },- })-- const { state: next } = await paginator.processPage(team.id, state, {- jobId: 'test-rerun-job',- createdAt: DateTime.now(),- })- expect(next.progress.queued).toBe(0)- expect(next.progress.skipped).toBe(1)- expect(next.progress.done).toBe(true)- expect(next.progress.last_error).toBeUndefined()+ expect(hogQueue.queueInvocations).not.toHaveBeenCalled()})})@@ -508,7 +482,7 @@ describe('RerunPaginatorService integration', () => {hogFlowManager,hogInputsService,paginatorLifecycleService,- cyclotronJobQueue,+ { hog_function: hogQueue, hog_flow: hogflowQueue },paginatorMonitoringService,10000)@@ -530,7 +504,7 @@ describe('RerunPaginatorService integration', () => {})expect(next.progress.done).toBe(false)expect(next.progress.last_error).toContain('clickhouse boom')- expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()+ expect(hogQueue.queueInvocations).not.toHaveBeenCalled()})})@@ -587,7 +561,7 @@ describe('RerunPaginatorService integration', () => {createdAt: DateTime.now(),})- const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const enqueued = hogQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]expect(enqueued).toHaveLength(1)// CH returns DateTime64 as 'YYYY-MM-DD HH:MM:SS.ffffff' — just check// the date portion matches the original scheduled time. The exactdiff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.tsindex 64498ee93a3d..eb3e96919624 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts@@ -8,7 +8,8 @@ import { CyclotronJobConflictError } from '../services/cyclotron-v2'import { HogInputsService } from '../services/hog-inputs.service'import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'-import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'+import { JobQueue } from '../services/job-queue/job-queue.interface'import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'@@ -71,6 +72,17 @@ export interface PageOutcome {state: RerunJobState}+/**+ * Re-enqueue targets keyed by rerun function kind. Mirrors the split in+ * cdp-events-consumer — hog functions go to kafka, hog flows to postgres-v2.+ * Keying by kind (rather than two positional queue args of similar shape)+ * stops the two backends from being swapped by mistake.+ */+export interface RerunJobQueues {+ hog_function: JobQueue+ hog_flow: CyclotronJobQueuePostgresV2+}+/*** Context the worker passes alongside the parsed state on each page. Lets the* paginator stamp wrapper lifecycle rows with the right `invocation_id`@@ -95,7 +107,8 @@ export class RerunPaginatorService {private hogFlowManager: HogFlowManagerService,private hogInputsService: HogInputsService,private invocationResultsRowsService: HogInvocationResultsService,- private cyclotronJobQueue: CyclotronJobQueue,+ // Re-enqueue targets keyed by function kind — see RerunJobQueues.+ private jobQueues: RerunJobQueues,private monitoringService: HogFunctionMonitoringService,// Mirror of the Django serializer cap (HOG_INVOCATION_RERUN_MAX_COUNT env var).private maxCount: number@@ -120,42 +133,47 @@ export class RerunPaginatorService {let conflictSkipped = 0if (queuedInvocations.length > 0) {- // Rerun re-uses the original invocation_id. Routing is the- // same as cdp-events-consumer (`getTarget()` per invocation —- // hog → kafka, hog_flow → postgres-v2). `overwriteExisting`- // only matters for the v2 path: it upserts ONLY when the- // existing cyclotron row is in a terminal state. If a v2-- // routed invocation's row is still active, the v2 manager- // raises CyclotronJobConflictError listing the conflicting- // ids — skip those, still queue the rest. Kafka-routed- // invocations can't conflict (no PK) and v1 is unsupported- // for rerun (throws at the queue boundary).+ // Rerun re-uses the original invocation_id. A rerun job is+ // scoped to a single function kind, so the whole page routes to+ // one backend — hog → kafka, hog_flow → postgres-v2, the same+ // split cdp-events-consumer uses.let invocationsToEnqueue = queuedInvocations- try {- await this.cyclotronJobQueue.queueInvocations(invocationsToEnqueue, {- overwriteExisting: true,- })- } catch (e) {- if (!(e instanceof CyclotronJobConflictError)) {- throw e- }- const raw = e.conflictingIds- const conflictingIds = new Set(Array.isArray(raw) ? raw : [raw])- logger.warn('Rerun skipping invocations that are still in-flight', {- rerun_function_kind: function_kind,- rerun_function_id: function_id,- conflicting_invocation_ids: Array.from(conflictingIds),- })- conflictSkipped = conflictingIds.size- for (let i = 0; i < conflictSkipped; i++) {- counterRerunInvocationsSkipped.labels(function_kind, 'still_in_flight').inc()+ if (function_kind === 'hog_flow') {+ // postgres-v2. `overwriteExisting` upserts ONLY when the+ // existing cyclotron row is in a terminal state. If a row+ // is still active, the v2 manager raises+ // CyclotronJobConflictError listing the conflicting ids —+ // skip those, still queue the rest.+ try {+ await this.jobQueues.hog_flow.queueInvocations(invocationsToEnqueue, {+ overwriteExisting: true,+ })+ } catch (e) {+ if (!(e instanceof CyclotronJobConflictError)) {+ throw e+ }+ const raw = e.conflictingIds+ const conflictingIds = new Set(Array.isArray(raw) ? raw : [raw])+ logger.warn('Rerun skipping invocations that are still in-flight', {+ rerun_function_kind: function_kind,+ rerun_function_id: function_id,+ conflicting_invocation_ids: Array.from(conflictingIds),+ })+ conflictSkipped = conflictingIds.size+ for (let i = 0; i < conflictSkipped; i++) {+ counterRerunInvocationsSkipped.labels(function_kind, 'still_in_flight').inc()+ }+ // The conflicting invocations also queued a 'running'+ // lifecycle row above — drop them so we don't show a+ // stale running row for an invocation that didn't+ // actually re-enqueue.+ invocationsToEnqueue = queuedInvocations.filter((i) => !conflictingIds.has(i.id))+ this.invocationResultsRowsService.dropQueuedRowsFor(Array.from(conflictingIds))}- // The conflicting invocations also queued a 'running'- // lifecycle row above — drop them so we don't show a stale- // running row for an invocation that didn't actually- // re-enqueue.- invocationsToEnqueue = queuedInvocations.filter((i) => !conflictingIds.has(i.id))- this.invocationResultsRowsService.dropQueuedRowsFor(Array.from(conflictingIds))+ } else {+ // kafka. No PK, so a re-enqueue with the original+ // invocation_id can't conflict — no overwrite path needed.+ await this.jobQueues.hog_function.queueInvocations(invocationsToEnqueue)}await this.invocationResultsRowsService.flush()counterRerunInvocationsQueued.labels(function_kind).inc(invocationsToEnqueue.length)diff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.test.tsindex 3f95a64e547a..8223893a0cba 100644--- a/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'import { mockFetch } from '~/tests/helpers/mocks/request.mock'@@ -58,7 +59,10 @@ describe('BatchExportHogFunctionService', () => {hub = await createHub({ SITE_URL: 'http://localhost:8000' })team = await getFirstTeam(hub.postgres)- api = new CdpApi(hub, createCdpConsumerDeps(hub))+ api = new CdpApi(hub, createCdpConsumerDeps(hub), {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })app = setupExpressApp()app.use('/', api.router())server = app.listen(0, () => {})diff --git a/nodejs/src/cdp/services/job-queue/job-queue-kafka.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-kafka.test.tsindex 0fb17a747e31..cc70baf9fc4f 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-kafka.test.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-kafka.test.ts@@ -1,6 +1,6 @@import { migrateKafkaCyclotronInvocation } from './job-queue-kafka'-describe('CyclotronJobQueue - kafka', () => {+describe('CyclotronJobQueueKafka', () => {describe('migrateKafkaCyclotronInvocation', () => {// Pulled from a real job in kafkaconst legacyFormat = {diff --git a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts b/nodejs/src/cdp/services/job-queue/job-queue-kafka.tsindex f0492a282e1e..5257028e80fc 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts@@ -13,24 +13,33 @@ import { parseJSON } from '../../../utils/json-parse'import { logger } from '../../../utils/logger'import { CdpConfig } from '../../config'import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'-import { cdpJobSizeCompressedKb, cdpJobSizeKb } from './shared'+import { JobQueue } from './job-queue.interface'+import { cdpJobSizeCompressedKb, cdpJobSizeKb, createInvocationSanitizer } from './shared'-export class CyclotronJobQueueKafka {+export class CyclotronJobQueueKafka implements JobQueue {private kafkaConsumer?: KafkaConsumerInterfaceprivate kafkaProducer?: KafkaProducerWrapperprivate queue?: CyclotronJobQueueKindprivate consumeBatch?: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>+ private sanitizer: ReturnType<typeof createInvocationSanitizer>constructor(private kafkaClientRack: string | undefined,- private config: Pick<CdpConfig, 'CDP_CYCLOTRON_COMPRESS_KAFKA_DATA'>- ) {}+ private config: Pick<+ CdpConfig,+ 'CDP_CYCLOTRON_COMPRESS_KAFKA_DATA' | 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'+ >+ ) {+ this.sanitizer = createInvocationSanitizer(config)+ }/*** Helper to only start the producer related code (e.g. when not a consumer)*/public async startAsProducer() {- // NOTE: For producing we use different values dedicated for Cyclotron as this is typically using its own Kafka cluster+ if (this.kafkaProducer) {+ return+ }this.kafkaProducer = await KafkaProducerWrapper.create(this.kafkaClientRack, 'CDP_PRODUCER')}@@ -56,10 +65,12 @@ export class CyclotronJobQueueKafka {public async stopConsumer() {await this.kafkaConsumer?.disconnect()+ this.kafkaConsumer = undefined}public async stopProducer() {await this.kafkaProducer?.disconnect()+ this.kafkaProducer = undefined}public isHealthy(): HealthCheckResult {@@ -78,7 +89,7 @@ export class CyclotronJobQueueKafka {// Pre-serialize all messages eagerly so the produce closures below only// capture lightweight strings instead of full invocation objects (globals, vmState, etc.)- const messages = invocations.map((x) => {+ const messages = this.sanitizer.sanitizeInvocations(invocations).map((x) => {const jsonString = JSON.stringify(serializeInvocation(x))cdpJobSizeKb.labels('kafka').observe(jsonString.length / 1024)@@ -127,6 +138,10 @@ export class CyclotronJobQueueKafka {)}+ // Kafka jobs don't need explicit dequeue/cancel — they're just dropped+ public async dequeueInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}+ public async cancelInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}+public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {// With kafka we are essentially re-queuing the work to the target topic if it isn't finishedconst invocations: CyclotronJobInvocation[] = []diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.tsindex f4618c3e1af1..640e94bea04f 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts@@ -9,7 +9,8 @@ import { logger } from '../../../utils/logger'import { CdpConfig } from '../../config'import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'import { CyclotronV2DequeuedJob, CyclotronV2JobInit, CyclotronV2Manager, CyclotronV2Worker } from '../cyclotron-v2'-import { cdpJobSizeCompressedKb, cdpJobSizeKb } from './shared'+import { JobQueue } from './job-queue.interface'+import { cdpJobSizeCompressedKb, cdpJobSizeKb, createInvocationSanitizer } from './shared'const pendingJobsGauge = new Gauge({name: 'cdp_cyclotron_v2_pending_jobs',@@ -26,10 +27,11 @@ type SerializedJobState = {queueMetadata?: CyclotronJobInvocation['queueMetadata']}-export class CyclotronJobQueuePostgresV2 {+export class CyclotronJobQueuePostgresV2 implements JobQueue {private manager?: CyclotronV2Managerprivate worker?: CyclotronV2Workerprivate pendingJobs = new Map<string, CyclotronV2DequeuedJob>()+ private sanitizer: ReturnType<typeof createInvocationSanitizer>constructor(private consumerBatchSize: number,@@ -40,10 +42,16 @@ export class CyclotronJobQueuePostgresV2 {| 'CDP_CYCLOTRON_BATCH_DELAY_MS'| 'CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE'| 'CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES'+ | 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'>- ) {}+ ) {+ this.sanitizer = createInvocationSanitizer(config)+ }public async startAsProducer(): Promise<void> {+ if (this.manager) {+ return+ }if (!this.config.CYCLOTRON_NODE_DATABASE_URL) {throw new Error('Cyclotron V2 database URL not set')}@@ -91,10 +99,12 @@ export class CyclotronJobQueuePostgresV2 {public async stopConsumer(): Promise<void> {await this.worker?.disconnect()+ this.worker = undefined}public async stopProducer(): Promise<void> {await this.manager?.disconnect()+ this.manager = undefined}public isHealthy(): HealthCheckResult {@@ -119,6 +129,8 @@ export class CyclotronJobQueuePostgresV2 {throw new Error('CyclotronV2Manager not initialized')}+ invocations = this.sanitizer.sanitizeInvocations(invocations)+const jobs = invocations.map((inv) => ({...invocationToV2JobInit(inv),overwriteExisting: options.overwriteExisting,@@ -158,8 +170,10 @@ export class CyclotronJobQueuePostgresV2 {}public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]): Promise<void> {+ const sanitizedResults = this.sanitizer.sanitizeResults(invocationResults)+await Promise.all(- invocationResults.map(async (result) => {+ sanitizedResults.map(async (result) => {const job = this.pendingJobs.get(result.invocation.id)if (!job) {logger.warn('No pending V2 job found for result, creating new job', {diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres.tsindex d22de536b64c..4cfd5679955a 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts@@ -22,11 +22,19 @@ import { logger } from '../../../utils/logger'import { captureException } from '../../../utils/posthog'import { CdpConfig } from '../../config'import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'+import { JobQueue } from './job-queue.interface'+import { createInvocationSanitizer } from './shared'-export class CyclotronJobQueuePostgres {+/**+ * Legacy postgres v1 queue via @posthog/cyclotron.+ * Only kept for draining old jobs — no new jobs are produced to v1.+ * Delete this file once the legacy worker is shut down.+ */+export class CyclotronJobQueuePostgres implements JobQueue {private cyclotronWorker?: CyclotronWorkerprivate cyclotronManager?: CyclotronManagerprivate consumeBatch?: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>+ private sanitizer: ReturnType<typeof createInvocationSanitizer>constructor(private consumerBatchSize: number,@@ -39,13 +47,19 @@ export class CyclotronJobQueuePostgres {| 'CDP_CYCLOTRON_BATCH_DELAY_MS'| 'CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE'| 'CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES'+ | 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'>- ) {}+ ) {+ this.sanitizer = createInvocationSanitizer(config)+ }/*** Helper to only start the producer related code (e.g. when not a consumer)*/public async startAsProducer() {+ if (this.cyclotronManager) {+ return+ }if (!this.config.CYCLOTRON_DATABASE_URL) {throw new Error('Cyclotron database URL not set! This is required for the CDP services to work.')}@@ -120,6 +134,8 @@ export class CyclotronJobQueuePostgres {return}+ invocations = this.sanitizer.sanitizeInvocations(invocations)+const cyclotronManager = this.getCyclotronManager()// For the cyclotron ones we simply create the jobs@@ -167,6 +183,7 @@ export class CyclotronJobQueuePostgres {}public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {+ invocationResults = this.sanitizer.sanitizeResults(invocationResults)const worker = this.getCyclotronWorker()await Promise.all(invocationResults.map((item) => {diff --git a/nodejs/src/cdp/services/job-queue/job-queue.interface.ts b/nodejs/src/cdp/services/job-queue/job-queue.interface.tsnew file mode 100644index 000000000000..f7ba70b5f07d--- /dev/null+++ b/nodejs/src/cdp/services/job-queue/job-queue.interface.ts@@ -0,0 +1,20 @@+import { HealthCheckResult } from '../../../types'+import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'++export type ConsumeBatchFn = (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>++/**+ * Common interface for job queue backends (Kafka, postgres-v2).+ * Each consumer gets the specific implementation it needs — no shared router.+ */+export interface JobQueue {+ startAsProducer(): Promise<void>+ startAsConsumer(queue: CyclotronJobQueueKind, consumeBatch: ConsumeBatchFn): Promise<void>+ stopConsumer(): Promise<void>+ stopProducer(): Promise<void>+ isHealthy(): HealthCheckResult+ queueInvocations(invocations: CyclotronJobInvocation[]): Promise<void>+ queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void>+ dequeueInvocations(invocations: CyclotronJobInvocation[]): Promise<void>+ cancelInvocations(invocations: CyclotronJobInvocation[]): Promise<void>+}diff --git a/nodejs/src/cdp/services/job-queue/job-queue.test.ts b/nodejs/src/cdp/services/job-queue/job-queue.test.tsdeleted file mode 100644index 90fb98299683..000000000000--- a/nodejs/src/cdp/services/job-queue/job-queue.test.ts+++ /dev/null@@ -1,626 +0,0 @@-import { DateTime } from 'luxon'--import { defaultConfig } from '~/config/config'-import { PluginsServerConfig } from '~/types'--import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../../_tests/examples'-import { createHogExecutionGlobals, createHogFunction } from '../../_tests/fixtures'-import { CyclotronJobInvocationResult, CyclotronJobQueueSource } from '../../types'-import { createInvocation } from '../../utils/invocation-utils'-import {- CyclotronJobQueue,- JOB_SCHEDULED_AT_FUTURE_THRESHOLD_MS,- getProducerMapping,- getProducerTeamMapping,-} from './job-queue'--describe('CyclotronJobQueue', () => {- let config: PluginsServerConfig- const exampleHogFunction = createHogFunction({- name: 'Test hog function',- ...HOG_EXAMPLES.simple_fetch,- ...HOG_INPUTS_EXAMPLES.simple_fetch,- ...HOG_FILTERS_EXAMPLES.no_filters,- })-- beforeEach(() => {- config = { ...defaultConfig }- })-- it('should initialise', () => {- const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)- expect(queue).toBeDefined()- })-- describe('v2 client validation', () => {- it.each([- {- description: 'producer mapping routes to postgres-v2 but v2 URL is not set',- v2URL: undefined as string | undefined,- producerMapping: '*:kafka,hogflow:postgres-v2',- producerTeamMapping: '',- expectThrow: /CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING routes to postgres-v2/,- },- {- description: 'producer team mapping routes to postgres-v2 but v2 URL is not set',- v2URL: undefined as string | undefined,- producerMapping: '*:kafka',- producerTeamMapping: '1:*:kafka,1:hogflow:postgres-v2',- expectThrow: /CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING routes to postgres-v2/,- },- {- description: 'producer mapping routes to postgres-v2 and v2 URL is set',- v2URL: 'postgres://localhost:5432',- producerMapping: '*:kafka,hogflow:postgres-v2',- producerTeamMapping: '',- expectThrow: null,- },- {- description: 'producer mapping does not route to postgres-v2 and v2 URL is not set',- v2URL: undefined as string | undefined,- producerMapping: '*:kafka,hogflow:kafka',- producerTeamMapping: '',- expectThrow: null,- },- ])('$description', ({ v2URL, producerMapping, producerTeamMapping, expectThrow }) => {- config.CYCLOTRON_NODE_DATABASE_URL = v2URL- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = producerMapping- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING = producerTeamMapping- const create = () => new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)- if (expectThrow) {- expect(create).toThrow(expectThrow)- } else {- expect(create).not.toThrow()- }- })- })-- describe('producer setup', () => {- const buildQueue = (mapping: string, teamMapping?: string) => {- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = mapping- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING = teamMapping || ''- const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)- queue['jobQueuePostgres'].startAsProducer = jest.fn()- queue['jobQueueKafka'].startAsProducer = jest.fn()- queue['jobQueuePostgres'].queueInvocations = jest.fn()- queue['jobQueueKafka'].queueInvocations = jest.fn()- return queue- }-- it('should start only kafka producer if only kafka is mapped', async () => {- const queue = buildQueue('*:kafka,hogflow:kafka')- await queue.startAsProducer()- expect(queue['jobQueuePostgres'].startAsProducer).not.toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()- })-- it('should start only postgres producer if only postgres is mapped', async () => {- const queue = buildQueue('*:postgres,hogflow:postgres')- await queue.startAsProducer()- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).not.toHaveBeenCalled()- })-- it('should start both producers if both are mapped', async () => {- const queue = buildQueue('*:postgres,hogflow:kafka')- await queue.startAsProducer()- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()- })-- it('should start both producers if split routing is mapped', async () => {- const queue = buildQueue('*:postgres:0.5,*:kafka:0.5')- await queue.startAsProducer()- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()- })-- it('should account for team mapping', async () => {- const queue = buildQueue('*:postgres', '1:*:kafka')- await queue.startAsProducer()- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()- })-- describe('team-specific percentage routing', () => {- let queue: CyclotronJobQueue-- beforeEach(async () => {- queue = buildQueue('*:kafka', '79155:*:kafka,79155:hog:postgres-v2:0.001')- queue['jobQueuePostgresV2'] = {- startAsProducer: jest.fn(),- queueInvocations: jest.fn(),- } as any- await queue.startAsProducer()- })-- afterEach(() => {- jest.restoreAllMocks()- })-- const team79155HogFunction = createHogFunction({- ...HOG_EXAMPLES.simple_fetch,- ...HOG_INPUTS_EXAMPLES.simple_fetch,- ...HOG_FILTERS_EXAMPLES.no_filters,- team_id: 79155,- })-- it('should route hog jobs to postgres-v2 when roll is below percentage', async () => {- jest.spyOn(Math, 'random').mockReturnValue(0.0005)- const invocation = createInvocation(- { ...createHogExecutionGlobals(), inputs: {} },- team79155HogFunction- )- await queue.queueInvocations([invocation])-- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(- [expect.objectContaining({ teamId: 79155, queue: 'hog' })],- { overwriteExisting: undefined }- )- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([])- })-- it('should route hog jobs to kafka when roll exceeds percentage', async () => {- jest.spyOn(Math, 'random').mockReturnValue(0.5)- const invocation = createInvocation(- { ...createHogExecutionGlobals(), inputs: {} },- team79155HogFunction- )- await queue.queueInvocations([invocation])-- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {- overwriteExisting: undefined,- })- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ teamId: 79155, queue: 'hog' }),- ])- })-- it('should route non-hog queues to the team default', async () => {- const invocation = {- ...createInvocation({ ...createHogExecutionGlobals(), inputs: {} }, team79155HogFunction),- queue: 'hogflow' as const,- }- await queue.queueInvocations([invocation])-- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ teamId: 79155, queue: 'hogflow' }),- ])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {- overwriteExisting: undefined,- })- })-- it('should not affect other teams', async () => {- jest.spyOn(Math, 'random').mockReturnValue(0.0005)- const invocation = createInvocation(- { ...createHogExecutionGlobals(), inputs: {} },- exampleHogFunction // team_id defaults to 1- )- await queue.queueInvocations([invocation])-- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ teamId: 1, queue: 'hog' }),- ])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {- overwriteExisting: undefined,- })- })- })-- it.each([- ['postgres', true],- ['kafka', false],- ])(- 'should route scheduled jobs to %s if force scheduled to postgres is enabled',- async (_target, enforceRouting) => {- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES = enforceRouting- const queue = buildQueue('*:kafka')- await queue.startAsProducer()- const invocations = [- {- ...createInvocation(- {- ...createHogExecutionGlobals(),- inputs: {},- },- exampleHogFunction- ),- queueScheduledAt: DateTime.now().plus({- milliseconds: JOB_SCHEDULED_AT_FUTURE_THRESHOLD_MS + 1000,- }),- },- ]- await queue.queueInvocations(invocations)-- if (enforceRouting) {- // With enforced routing and the main queue being kafka then both producers should be started- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()-- expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith(invocations)- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([])- } else {- // Without enforced routing only the kafka producer should be started- expect(queue['jobQueuePostgres'].startAsProducer).not.toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()-- expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([])- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith(invocations)- }- }- )-- it('should not route scheduled jobs to postgres if they are not scheduled far enough in the future', async () => {- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES = true-- const queue = buildQueue('*:kafka')- await queue.startAsProducer()- const invocations = [- {- ...createInvocation(- {- ...createHogExecutionGlobals(),- inputs: {},- },- exampleHogFunction- ),- queueScheduledAt: DateTime.now().plus({- milliseconds: JOB_SCHEDULED_AT_FUTURE_THRESHOLD_MS - 1000,- }),- },- ]- await queue.queueInvocations(invocations)-- // With enforced routing and the main queue being kafka then both producers should be started- expect(queue['jobQueuePostgres'].startAsProducer).toHaveBeenCalled()- expect(queue['jobQueueKafka'].startAsProducer).toHaveBeenCalled()-- expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([])- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith(invocations)- })- })-- describe('queueInvocationResults', () => {- const buildQueue = (mapping: string) => {- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = mapping- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING = ''- const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)-- // Mock all sub-queue methods- queue['jobQueuePostgres'].queueInvocations = jest.fn()- queue['jobQueuePostgres'].queueInvocationResults = jest.fn()- queue['jobQueuePostgres'].releaseInvocations = jest.fn()- queue['jobQueueKafka'].queueInvocations = jest.fn()- queue['jobQueueKafka'].queueInvocationResults = jest.fn()- queue['jobQueuePostgresV2'] = {- queueInvocations: jest.fn(),- queueInvocationResults: jest.fn(),- releaseInvocations: jest.fn(),- } as any-- return queue- }-- const createResult = (queueSource: CyclotronJobQueueSource): CyclotronJobInvocationResult => ({- invocation: {- ...createInvocation({ ...createHogExecutionGlobals(), inputs: {} }, exampleHogFunction),- queueSource,- },- finished: false,- error: null,- logs: [],- metrics: [],- capturedPostHogEvents: [],- warehouseWebhookPayloads: [],- })-- it.each([- {- scenario: 'postgres-v2 source routed to postgres target',- mapping: '*:postgres',- queueSource: 'postgres-v2' as const,- expectReleasedFrom: 'jobQueuePostgresV2',- },- {- scenario: 'postgres source routed to postgres-v2 target',- mapping: '*:postgres-v2',- queueSource: 'postgres' as const,- expectReleasedFrom: 'jobQueuePostgres',- },- {- scenario: 'postgres source routed to kafka target',- mapping: '*:kafka',- queueSource: 'postgres' as const,- expectReleasedFrom: 'jobQueuePostgres',- },- {- scenario: 'postgres-v2 source routed to kafka target',- mapping: '*:kafka',- queueSource: 'postgres-v2' as const,- expectReleasedFrom: 'jobQueuePostgresV2',- },- ])(- 'should release source job when cross-routing: $scenario',- async ({ mapping, queueSource, expectReleasedFrom }) => {- const queue = buildQueue(mapping)- const result = createResult(queueSource)-- await queue.queueInvocationResults([result])-- expect(- (queue[expectReleasedFrom as keyof typeof queue] as any).releaseInvocations- ).toHaveBeenCalledTimes(1)- }- )-- it.each([- { mapping: '*:postgres', queueSource: 'postgres' as const },- { mapping: '*:postgres-v2', queueSource: 'postgres-v2' as const },- ])(- 'should not release when source matches target: $mapping / $queueSource',- async ({ mapping, queueSource }) => {- const queue = buildQueue(mapping)- const result = createResult(queueSource)-- await queue.queueInvocationResults([result])-- // Should update, not create+release- expect(queue['jobQueuePostgres'].releaseInvocations).not.toHaveBeenCalled()- expect(queue['jobQueuePostgresV2']!.releaseInvocations).not.toHaveBeenCalled()- }- )- })-- describe('rerun routing (overwriteExisting)', () => {- const buildQueueWithMocks = (mapping: string): CyclotronJobQueue => {- config.CYCLOTRON_NODE_DATABASE_URL = 'postgres://localhost:5432'- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = mapping- const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)- queue['jobQueuePostgres'].queueInvocations = jest.fn()- queue['jobQueueKafka'].queueInvocations = jest.fn()- queue['jobQueuePostgresV2'] = {- startAsProducer: jest.fn(),- queueInvocations: jest.fn(),- } as any- return queue- }-- const hogInvocation = () => createInvocation({ ...createHogExecutionGlobals(), inputs: {} }, exampleHogFunction)- const hogflowInvocation = () => ({ ...hogInvocation(), queue: 'hogflow' as const })-- it('routes hog → kafka under the standard mapping (no overwrite passed through)', async () => {- const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')- const inv = hogInvocation()-- await queue.queueInvocations([inv], { overwriteExisting: true })-- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ queue: 'hog' }),- ])- // The v2 producer is only called with the v2-routed slice, which here is empty.- // `overwriteExisting` is irrelevant when nothing routes there.- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], { overwriteExisting: true })- })-- it('preserves the invocation_id through the kafka rerun path', async () => {- const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')- const inv = hogInvocation()- const originalId = inv.id-- await queue.queueInvocations([inv], { overwriteExisting: true })-- // The rerun paginator sets `id: row.invocation_id` on the rehydrated- // invocation; this asserts the routing path doesn't generate a new- // UUID before producing to kafka, so lifecycle rows for the rerun- // run collapse onto the same key in CH.- const enqueued = (queue['jobQueueKafka'].queueInvocations as jest.Mock).mock.calls[0][0]- expect(enqueued).toHaveLength(1)- expect(enqueued[0].id).toBe(originalId)- })-- it('preserves the invocation_id through the postgres-v2 rerun path', async () => {- const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')- const inv = hogflowInvocation()- const originalId = inv.id-- await queue.queueInvocations([inv], { overwriteExisting: true })-- const enqueued = (queue['jobQueuePostgresV2']!.queueInvocations as jest.Mock).mock.calls[0][0]- expect(enqueued).toHaveLength(1)- expect(enqueued[0].id).toBe(originalId)- })-- it('routes hogflow → postgres-v2 with overwriteExisting forwarded', async () => {- const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')- const inv = hogflowInvocation()-- await queue.queueInvocations([inv], { overwriteExisting: true })-- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(- [expect.objectContaining({ queue: 'hogflow' })],- { overwriteExisting: true }- )- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([])- })-- it('splits mixed batches across kafka + v2 under per-queue routing', async () => {- const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')-- await queue.queueInvocations([hogInvocation(), hogflowInvocation(), hogInvocation()], {- overwriteExisting: true,- })-- expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ queue: 'hog' }),- expect.objectContaining({ queue: 'hog' }),- ])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(- [expect.objectContaining({ queue: 'hogflow' })],- { overwriteExisting: true }- )- expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([])- })-- it('throws for invocations routed to postgres-v1 under overwriteExisting', async () => {- const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')- const inv = hogInvocation()-- await expect(queue.queueInvocations([inv], { overwriteExisting: true })).rejects.toThrow(- /Rerun routing to postgres-v1 is unsupported \(queue=hog\)/- )- })-- it('still throws on v1 even when only one of N invocations targets v1', async () => {- const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')-- await expect(- queue.queueInvocations([hogflowInvocation(), hogInvocation()], { overwriteExisting: true })- ).rejects.toThrow(/postgres-v1 is unsupported/)- })-- it('allows v1 routing when overwriteExisting is NOT set (normal traffic path)', async () => {- const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')- const inv = hogInvocation()-- await expect(queue.queueInvocations([inv])).resolves.toBeUndefined()- expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ queue: 'hog' }),- ])- })-- it('throws if anything is routed to postgres-v2 but v2 was never constructed', async () => {- // No CYCLOTRON_NODE_DATABASE_URL → v2 stays unconstructed.- config.CYCLOTRON_NODE_DATABASE_URL = undefined- config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = '*:kafka'- const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)- queue['jobQueuePostgres'].queueInvocations = jest.fn()- queue['jobQueueKafka'].queueInvocations = jest.fn()- // Force a v2-targeted invocation by patching the router.- jest.spyOn(queue as any, 'getTarget').mockReturnValue('postgres-v2' as CyclotronJobQueueSource)-- await expect(queue.queueInvocations([hogInvocation()])).rejects.toThrow(/cyclotron-v2 is not configured/)- })- })-})--describe('getProducerMapping', () => {- it.each([- [- '*:kafka',- {- '*': [{ target: 'kafka', percentage: 1 }],- },- ],- [- '*:kafka:0.5,*:postgres:0.5,hog:kafka,hogflow:postgres:0.1,hogflow:kafka:0.9',- {- '*': [- { target: 'kafka', percentage: 0.5 },- { target: 'postgres', percentage: 0.5 },- ],- hog: [{ target: 'kafka', percentage: 1 }],- hogflow: [- { target: 'postgres', percentage: 0.1 },- { target: 'kafka', percentage: 0.9 },- ],- },- ],- ])('should return the correct mapping for %s', (mapping, expected) => {- expect(getProducerMapping(mapping)).toEqual(expected)- })-- it.each([- ['*:kafkatypo', 'Invalid mapping: *:kafkatypo - target kafkatypo must be one of postgres, postgres-v2, kafka'],- [- 'hog:kafkatypo',- 'Invalid mapping: hog:kafkatypo - target kafkatypo must be one of postgres, postgres-v2, kafka',- ],- [- 'hog:kafka,hogflow:postgres,*:kafkatypo',- 'Invalid mapping: *:kafkatypo - target kafkatypo must be one of postgres, postgres-v2, kafka',- ],- [- 'wrong_queue:kafka',- 'Invalid mapping: wrong_queue:kafka - queue wrong_queue must be one of *, hog, hogoverflow, hogflow',- ],- ['hog:kafka:1.1', 'Invalid mapping: hog:kafka:1.1 - percentage 1.1 must be 0 < x <= 1'],- ['hog:kafka', 'No mapping for the default queue for example: *:postgres'],- ['*:kafka:0.5,*:postgres:0.3', 'Invalid mapping for queue *: percentages must sum to 1 (got 0.8)'],- ])('should throw for bad values for %s', (mapping, error) => {- expect(() => getProducerMapping(mapping)).toThrow(error)- })-})--describe('getProducerTeamMapping', () => {- it('should return empty object for empty string', () => {- expect(getProducerTeamMapping('')).toEqual({})- })-- it('should parse a single team with a default queue', () => {- expect(getProducerTeamMapping('1:*:postgres')).toEqual({- '1': {- '*': [{ target: 'postgres', percentage: 1 }],- },- })- })-- it('should parse multiple teams', () => {- expect(getProducerTeamMapping('1:*:kafka,2:*:postgres')).toEqual({- '1': {- '*': [{ target: 'kafka', percentage: 1 }],- },- '2': {- '*': [{ target: 'postgres', percentage: 1 }],- },- })- })-- it('should fill remainder from team * default', () => {- const result = getProducerTeamMapping('79155:*:kafka,79155:hog:postgres-v2:0.001')- expect(result['79155']['hog']).toHaveLength(2)- expect(result['79155']['hog'][0]).toEqual({ target: 'postgres-v2', percentage: 0.001 })- expect(result['79155']['hog'][1].target).toBe('kafka')- expect(result['79155']['hog'][1].percentage).toBeCloseTo(0.999)- })-- it('should fill remainder proportionally from multi-target * default', () => {- const result = getProducerTeamMapping('79155:*:kafka:0.7,79155:*:postgres:0.3,79155:hog:postgres-v2:0.1')- expect(result['79155']['hog']).toHaveLength(3)- expect(result['79155']['hog'][0]).toEqual({ target: 'postgres-v2', percentage: 0.1 })- expect(result['79155']['hog'][1].target).toBe('kafka')- expect(result['79155']['hog'][1].percentage).toBeCloseTo(0.63)- expect(result['79155']['hog'][2].target).toBe('postgres')- expect(result['79155']['hog'][2].percentage).toBeCloseTo(0.27)- })-- it('should not fill remainder when percentages already sum to 1', () => {- const result = getProducerTeamMapping('79155:*:kafka,79155:hog:postgres-v2:0.5,79155:hog:kafka:0.5')- expect(result['79155']['hog']).toEqual([- { target: 'postgres-v2', percentage: 0.5 },- { target: 'kafka', percentage: 0.5 },- ])- })-- it('should reject team mappings with percentages exceeding 1', () => {- expect(() => getProducerTeamMapping('79155:*:kafka,79155:hog:postgres-v2:0.6,79155:hog:kafka:0.6')).toThrow(- 'percentages must sum to 1'- )- })-- it('should handle multiple teams with multiple queues', () => {- const result = getProducerTeamMapping('1:*:kafka,1:hog:postgres:0.5,1:hog:kafka:0.5,2:*:postgres')- expect(result['1']['*']).toEqual([{ target: 'kafka', percentage: 1 }])- expect(result['1']['hog']).toEqual([- { target: 'postgres', percentage: 0.5 },- { target: 'kafka', percentage: 0.5 },- ])- expect(result['2']['*']).toEqual([{ target: 'postgres', percentage: 1 }])- })-- it('should throw for malformed entries', () => {- expect(() => getProducerTeamMapping('79155')).toThrow(- 'Invalid team mapping: 79155 - expected format TEAM:QUEUE:TARGET[:PERCENTAGE]'- )- })-})diff --git a/nodejs/src/cdp/services/job-queue/job-queue.ts b/nodejs/src/cdp/services/job-queue/job-queue.tsdeleted file mode 100644index 1cd2637eb692..000000000000--- a/nodejs/src/cdp/services/job-queue/job-queue.ts+++ /dev/null@@ -1,598 +0,0 @@-/**- * NOTE: We are often experimenting with different job queue implementations.- * To make this easier this class is designed to abstract the queue as much as possible from- * the underlying implementation.- */-import { DateTime } from 'luxon'-import { Counter, Gauge } from 'prom-client'--import { instrumentFn } from '~/common/tracing/tracing-utils'--import { buildIntegerMatcher } from '../../../config/config'-import { HealthCheckResultError, ValueMatcher } from '../../../types'-import { logger } from '../../../utils/logger'-import { CdpConfig } from '../../config'-import {- CYCLOTRON_INVOCATION_JOB_QUEUES,- CYCLOTRON_JOB_QUEUE_SOURCES,- CyclotronJobInvocation,- CyclotronJobInvocationResult,- CyclotronJobQueueKind,- CyclotronJobQueueSource,-} from '../../types'-import { CyclotronJobQueueKafka } from './job-queue-kafka'-import { CyclotronJobQueuePostgres } from './job-queue-postgres'-import { CyclotronJobQueuePostgresV2 } from './job-queue-postgres-v2'-import { sanitizeInvocationForPersistence } from './shared'--const cyclotronBatchUtilizationGauge = new Gauge({- name: 'cdp_cyclotron_batch_utilization',- help: 'Indicates how big batches are we are processing compared to the max batch size. Useful as a scaling metric',- labelNames: ['queue', 'source'],-})--const counterJobsProcessed = new Counter({- name: 'cdp_cyclotron_jobs_processed',- help: 'The number of jobs we are managing to process',- labelNames: ['queue', 'source'],-})--export const JOB_SCHEDULED_AT_FUTURE_THRESHOLD_MS = 10 * 1000 // Any scheduled jobs need to be scheduled this much in the future to be considered for postgres-const PERCENTAGE_TOLERANCE = 0.001--export type CyclotronJobQueueRoutingEntry = {- target: CyclotronJobQueueSource- percentage: number-}--export type CyclotronJobQueueRouting = {- [key: string]: CyclotronJobQueueRoutingEntry[]-}--export type CyclotronJobQueueTeamRouting = {- [teamId: string]: CyclotronJobQueueRouting-}--export class CyclotronJobQueue {- private queue?: CyclotronJobQueueKind- private consumerMode?: CyclotronJobQueueSource- private _consumeBatch?: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>- private producerMapping: CyclotronJobQueueRouting- private producerTeamMapping: CyclotronJobQueueTeamRouting- private producerForceScheduledToPostgres: boolean- private jobQueuePostgres: CyclotronJobQueuePostgres- private jobQueuePostgresV2: CyclotronJobQueuePostgresV2 | null = null- private jobQueueKafka: CyclotronJobQueueKafka- private stripPersonMatcher: ValueMatcher<number>-- constructor(- private consumerBatchSize: number,- private kafkaClientRack: string | undefined,- private config: CdpConfig- ) {- this.producerMapping = getProducerMapping(this.config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING)- this.producerTeamMapping = getProducerTeamMapping(this.config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING)- this.producerForceScheduledToPostgres = this.config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_FORCE_SCHEDULED_TO_POSTGRES- this.stripPersonMatcher = buildIntegerMatcher(this.config.CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS, true)-- this.jobQueueKafka = new CyclotronJobQueueKafka(this.kafkaClientRack, this.config)- this.jobQueuePostgres = new CyclotronJobQueuePostgres(this.consumerBatchSize, this.config)-- if (this.config.CYCLOTRON_NODE_DATABASE_URL) {- this.jobQueuePostgresV2 = new CyclotronJobQueuePostgresV2(this.consumerBatchSize, this.config)- }-- // Without this, writes to postgres-v2 silently no-op via optional chaining,- // causing stall-reset loops and duplicate execution at the consumer side.- if (!this.jobQueuePostgresV2) {- const missingV2TargetError = (configKey: string): Error =>- new Error(- `${configKey} routes to postgres-v2 but CYCLOTRON_NODE_DATABASE_URL is not configured. ` +- `Set CYCLOTRON_NODE_DATABASE_URL (via psql.cyclotron in charts) or change the mapping to not target postgres-v2.`- )- if (routingReferencesV2(this.producerMapping)) {- throw missingV2TargetError('CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING')- }- for (const perTeamRouting of Object.values(this.producerTeamMapping)) {- if (routingReferencesV2(perTeamRouting)) {- throw missingV2TargetError('CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_TEAM_MAPPING')- }- }- }-- logger.info('🔄', 'CyclotronJobQueue initialized', {- producerMapping: this.producerMapping,- producerTeamMapping: this.producerTeamMapping,- v2Enabled: !!this.jobQueuePostgresV2,- })- }-- private async consumeBatch(- invocations: CyclotronJobInvocation[],- source: CyclotronJobQueueSource- ): Promise<{ backgroundTask: Promise<any> }> {- cyclotronBatchUtilizationGauge- .labels({ queue: this.queue!, source })- .set(invocations.length / this.consumerBatchSize)-- const result = await this._consumeBatch!(invocations)- counterJobsProcessed.inc({ queue: this.queue!, source }, invocations.length)-- return result- }- /**- * Helper to only start the producer related code (e.g. when not a consumer)- */- public async startAsProducer() {- // We only need to connect to the queue targets that are configured-- const allEntries: CyclotronJobQueueRoutingEntry[] = []-- for (const teamId in this.producerTeamMapping) {- for (const queue in this.producerTeamMapping[teamId]) {- allEntries.push(...this.producerTeamMapping[teamId][queue])- }- }-- for (const queue in this.producerMapping) {- allEntries.push(...this.producerMapping[queue])- }-- const targets = new Set<CyclotronJobQueueSource>(allEntries.map((x) => x.target))-- if (targets.has('postgres') || this.producerForceScheduledToPostgres) {- await this.jobQueuePostgres.startAsProducer()- }-- // Always start v2 when it's been constructed (which only happens when- // CYCLOTRON_NODE_DATABASE_URL is set). The routing mapping isn't the- // only path that reaches v2 — `queueInvocations({ overwriteExisting:- // true })` routes through v2 unconditionally for the rerun flow, so a- // service whose routing mapping doesn't reference v2 (the rerun- // worker, for instance) would still hit a 'CyclotronV2Manager not- // initialized' throw at first rerun if we gated on the mapping alone.- if (this.jobQueuePostgresV2) {- await this.jobQueuePostgresV2.startAsProducer()- }-- if (targets.has('kafka')) {- await this.jobQueueKafka.startAsProducer()- }- }-- public async start(- queue: CyclotronJobQueueKind,- consumeBatch: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>,- consumerMode?: CyclotronJobQueueSource- ) {- this.queue = queue- this._consumeBatch = consumeBatch- this.consumerMode = consumerMode ?? this.config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE-- // The consumer always needs the producers as well- await this.startAsProducer()-- if (this.consumerMode === 'postgres') {- await this.jobQueuePostgres.startAsConsumer(queue, (invocations) =>- this.consumeBatch(invocations, 'postgres')- )- } else if (this.consumerMode === 'postgres-v2') {- if (!this.jobQueuePostgresV2) {- throw new Error('Cyclotron V2 consumer mode requires CYCLOTRON_NODE_DATABASE_URL to be set')- }- await this.jobQueuePostgresV2.startAsConsumer(queue, (invocations) =>- this.consumeBatch(invocations, 'postgres-v2')- )- } else if (this.consumerMode === 'kafka') {- await this.jobQueueKafka.startAsConsumer(queue, (invocations) => this.consumeBatch(invocations, 'kafka'))- }- }-- public async stop() {- // Important - first shut down the consumers so we aren't processing anything- await Promise.all([- this.jobQueuePostgres.stopConsumer(),- this.jobQueuePostgresV2?.stopConsumer(),- this.jobQueueKafka.stopConsumer(),- ])-- // Only then do we shut down the producers- await Promise.all([- this.jobQueuePostgres.stopProducer(),- this.jobQueuePostgresV2?.stopProducer(),- this.jobQueueKafka.stopProducer(),- ])- }-- public isHealthy() {- if (!this.consumerMode) {- return new HealthCheckResultError('Consumer not started', {})- } else if (this.consumerMode === 'postgres') {- return this.jobQueuePostgres.isHealthy()- } else if (this.consumerMode === 'postgres-v2') {- return this.jobQueuePostgresV2?.isHealthy() ?? new HealthCheckResultError('V2 not enabled', {})- } else if (this.consumerMode === 'kafka') {- return this.jobQueueKafka.isHealthy()- }-- return new HealthCheckResultError('Invalid consumer mode', {})- }-- private getTarget(invocation: CyclotronJobInvocation): CyclotronJobQueueSource {- const teamId = invocation.teamId- const mapping = this.producerTeamMapping[teamId] ?? this.producerMapping- const entries = mapping[invocation.queue] ?? mapping['*']-- let target: CyclotronJobQueueSource- if (entries.length === 1) {- target = entries[0].target- } else {- const roll = Math.random()- let cumulative = 0- target = entries[entries.length - 1].target- for (const entry of entries) {- cumulative += entry.percentage- if (roll < cumulative) {- target = entry.target- break- }- }- }-- if (- target === 'kafka' &&- this.producerForceScheduledToPostgres &&- invocation.queueScheduledAt &&- invocation.queueScheduledAt > DateTime.now().plus({ milliseconds: JOB_SCHEDULED_AT_FUTURE_THRESHOLD_MS }) &&- invocation.queue !== 'hogoverflow' // overflow is always sent to kafka- ) {- // Kafka doesn't support delays so if enabled we should force scheduled jobs to postgres- return 'postgres'- }-- return target- }-- public async queueInvocations(- invocations: CyclotronJobInvocation[],- options: { overwriteExisting?: boolean } = {}- ) {- const sanitized = invocations.map((inv) =>- sanitizeInvocationForPersistence(inv, { stripPerson: this.stripPersonMatcher(inv.teamId) })- )-- const postgresInvocations: CyclotronJobInvocation[] = []- const postgresV2Invocations: CyclotronJobInvocation[] = []- const kafkaInvocations: CyclotronJobInvocation[] = []-- for (const invocation of sanitized) {- const target = this.getTarget(invocation)-- // Reruns carry `overwriteExisting: true` so a re-enqueue of an- // `invocation_id` that already has a cyclotron row doesn't fail- // on the PK. v2 supports it via ON CONFLICT, kafka doesn't need- // it (no PK at all), v1 has neither — so v1 + overwrite is an- // error rather than a silent fall-through.- if (target === 'postgres') {- if (options.overwriteExisting) {- throw new Error(- `Rerun routing to postgres-v1 is unsupported (queue=${invocation.queue}). ` +- `Route hog workloads to kafka and hog_flow workloads to postgres-v2.`- )- }- postgresInvocations.push(invocation)- } else if (target === 'postgres-v2') {- postgresV2Invocations.push(invocation)- } else {- kafkaInvocations.push(invocation)- }- }-- if (postgresV2Invocations.length > 0 && !this.jobQueuePostgresV2) {- throw new Error(`Invocations routed to postgres-v2 but cyclotron-v2 is not configured`)- }-- await Promise.all([- instrumentFn(- {- key: 'cyclotron.queue_invocations.postgres_v1',- sendException: false,- getLoggingContext: () => ({ count: postgresInvocations.length }),- },- () => this.jobQueuePostgres.queueInvocations(postgresInvocations)- ),- this.jobQueuePostgresV2- ? instrumentFn(- {- key: 'cyclotron.queue_invocations.postgres_v2',- sendException: false,- getLoggingContext: () => ({- count: postgresV2Invocations.length,- overwriteExisting: !!options.overwriteExisting,- }),- },- () =>- this.jobQueuePostgresV2!.queueInvocations(postgresV2Invocations, {- overwriteExisting: options.overwriteExisting,- })- )- : Promise.resolve(),- instrumentFn(- {- key: 'cyclotron.queue_invocations.kafka',- sendException: false,- getLoggingContext: () => ({ count: kafkaInvocations.length }),- },- () => this.jobQueueKafka.queueInvocations(kafkaInvocations)- ),- ])- }-- public async dequeueInvocations(invocations: CyclotronJobInvocation[]) {- // NOTE: This is only relevant to postgres backed jobs as kafka jobs can just be dropped- const pgJobsToDequeue = invocations.filter((x) => x.queueSource === 'postgres')- if (pgJobsToDequeue.length > 0) {- await this.jobQueuePostgres.dequeueInvocations(pgJobsToDequeue)- }-- const v2JobsToDequeue = invocations.filter((x) => x.queueSource === 'postgres-v2')- if (v2JobsToDequeue.length > 0) {- await this.jobQueuePostgresV2?.dequeueInvocations(v2JobsToDequeue)- }- }-- public async cancelInvocations(invocations: CyclotronJobInvocation[]) {- // NOTE: This is only relevant to postgres backed jobs as kafka jobs can just be dropped- const pgJobsToCancel = invocations.filter((x) => x.queueSource === 'postgres')- if (pgJobsToCancel.length > 0) {- await this.jobQueuePostgres.cancelInvocations(pgJobsToCancel)- }-- const v2JobsToCancel = invocations.filter((x) => x.queueSource === 'postgres-v2')- if (v2JobsToCancel.length > 0) {- await this.jobQueuePostgresV2?.cancelInvocations(v2JobsToCancel)- }- }-- public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {- // TODO: Routing based on queue name is slightly tricky here as postgres jobs need to be acked no matter what...- // We need to know if the job came from postgres and if so we need to ack, regardless of the target...-- const sanitizedResults = invocationResults.map((result) => ({- ...result,- invocation: sanitizeInvocationForPersistence(result.invocation, {- stripPerson: this.stripPersonMatcher(result.invocation.teamId),- }),- }))-- const postgresInvocationsToCreate: CyclotronJobInvocationResult[] = []- const postgresInvocationsToUpdate: CyclotronJobInvocationResult[] = []- const postgresV2InvocationsToUpdate: CyclotronJobInvocationResult[] = []- const postgresV2InvocationsToCreate: CyclotronJobInvocationResult[] = []- const kafkaInvocations: CyclotronJobInvocationResult[] = []-- for (const invocationResult of sanitizedResults) {- const target = this.getTarget(invocationResult.invocation)-- if (target === 'postgres') {- if (invocationResult.invocation.queueSource === 'postgres') {- postgresInvocationsToUpdate.push(invocationResult)- } else {- postgresInvocationsToCreate.push(invocationResult)- }- } else if (target === 'postgres-v2') {- if (invocationResult.invocation.queueSource === 'postgres-v2') {- postgresV2InvocationsToUpdate.push(invocationResult)- } else {- postgresV2InvocationsToCreate.push(invocationResult)- }- } else {- kafkaInvocations.push(invocationResult)- }- }-- logger.debug('🔄', 'Queueing invocation results', {- kafka: kafkaInvocations.map(- (x) => `${x.invocation.id} (queue:${x.invocation.queue},source:${x.invocation.queueSource})`- ),- postgres_update: postgresInvocationsToUpdate.map(- (x) => `${x.invocation.id} (queue:${x.invocation.queue},source:${x.invocation.queueSource})`- ),- postgres_create: postgresInvocationsToCreate.map(- (x) => `${x.invocation.id} (queue:${x.invocation.queue},source:${x.invocation.queueSource})`- ),- postgres_v2_update: postgresV2InvocationsToUpdate.map(- (x) => `${x.invocation.id} (queue:${x.invocation.queue},source:${x.invocation.queueSource})`- ),- postgres_v2_create: postgresV2InvocationsToCreate.map(- (x) => `${x.invocation.id} (queue:${x.invocation.queue},source:${x.invocation.queueSource})`- ),- })-- const promises: Promise<any>[] = []-- if (postgresInvocationsToUpdate.length > 0) {- promises.push(this.jobQueuePostgres.queueInvocationResults(postgresInvocationsToUpdate))- }-- if (postgresInvocationsToCreate.length > 0) {- promises.push(this.jobQueuePostgres.queueInvocations(postgresInvocationsToCreate.map((x) => x.invocation)))-- // Release postgres-v2 source jobs that are being re-routed to postgres- const v2JobsToRelease = postgresInvocationsToCreate- .filter((x) => x.invocation.queueSource === 'postgres-v2')- .map((x) => x.invocation)- if (v2JobsToRelease.length > 0 && this.jobQueuePostgresV2) {- promises.push(this.jobQueuePostgresV2.releaseInvocations(v2JobsToRelease))- }- }-- if (postgresV2InvocationsToUpdate.length > 0 && this.jobQueuePostgresV2) {- promises.push(this.jobQueuePostgresV2.queueInvocationResults(postgresV2InvocationsToUpdate))- }-- if (postgresV2InvocationsToCreate.length > 0 && this.jobQueuePostgresV2) {- promises.push(- this.jobQueuePostgresV2.queueInvocations(postgresV2InvocationsToCreate.map((x) => x.invocation))- )-- // Release postgres source jobs that are being re-routed to postgres-v2- const pgJobsToRelease = postgresV2InvocationsToCreate- .filter((x) => x.invocation.queueSource === 'postgres')- .map((x) => x.invocation)- if (pgJobsToRelease.length > 0) {- promises.push(this.jobQueuePostgres.releaseInvocations(pgJobsToRelease))- }- }-- if (kafkaInvocations.length > 0) {- promises.push(this.jobQueueKafka.queueInvocationResults(kafkaInvocations))-- const jobsToRelease = kafkaInvocations- .filter((x) => x.invocation.queueSource === 'postgres')- .map((x) => x.invocation)-- if (jobsToRelease.length > 0) {- promises.push(this.jobQueuePostgres.releaseInvocations(jobsToRelease))- }-- const v2JobsToRelease = kafkaInvocations- .filter((x) => x.invocation.queueSource === 'postgres-v2')- .map((x) => x.invocation)-- if (v2JobsToRelease.length > 0 && this.jobQueuePostgresV2) {- promises.push(this.jobQueuePostgresV2.releaseInvocations(v2JobsToRelease))- }- }-- await Promise.all(promises)- }-}--export function routingReferencesV2(routing: CyclotronJobQueueRouting): boolean {- return Object.values(routing).some((entries) => entries.some((e) => e.target === 'postgres-v2'))-}--/**- * Parses a mapping config from a string into a routing object.- * Format is like `QUEUE:TARGET:PERCENTAGE with percentage being optional and defaulting to 100- *- * So for example `*:kafka:10,fetch:postgres` would result in all fetch jobs being routed to postgres and 10% of all other jobs being routed to kafka and the rest to postgres- */-export function getProducerMapping(stringMapping: string): CyclotronJobQueueRouting {- const routing: CyclotronJobQueueRouting = {}- const parts = stringMapping.split(',')-- const validQueues = ['*', ...CYCLOTRON_INVOCATION_JOB_QUEUES]-- for (const part of parts) {- const [queue, target, percentageString] = part.split(':')-- if (!validQueues.includes(queue)) {- throw new Error(`Invalid mapping: ${part} - queue ${queue} must be one of ${validQueues.join(', ')}`)- }-- // change the type to the correct one once validated- if (!CYCLOTRON_JOB_QUEUE_SOURCES.includes(target as CyclotronJobQueueSource)) {- throw new Error(- `Invalid mapping: ${part} - target ${target} must be one of ${CYCLOTRON_JOB_QUEUE_SOURCES.join(', ')}`- )- }-- let percentage = 1-- if (percentageString) {- const parsedPercentage = parseFloat(percentageString)- if (isNaN(parsedPercentage) || parsedPercentage <= 0 || parsedPercentage > 1) {- throw new Error(`Invalid mapping: ${part} - percentage ${percentageString} must be 0 < x <= 1`)- }- percentage = parsedPercentage- }-- if (!routing[queue]) {- routing[queue] = []- }-- routing[queue].push({- target: target as CyclotronJobQueueSource,- percentage,- })- }-- if (!routing['*']) {- throw new Error('No mapping for the default queue for example: *:postgres')- }-- // Validate that percentages sum to 1 for multi-target queues- for (const [queue, entries] of Object.entries(routing)) {- if (entries.length > 1) {- const sum = entries.reduce((acc, e) => acc + e.percentage, 0)- if (Math.abs(sum - 1) > PERCENTAGE_TOLERANCE) {- throw new Error(`Invalid mapping for queue ${queue}: percentages must sum to 1 (got ${sum})`)- }- }- }-- return routing-}--/**- * Same as getProducerMapping but with a team prefix.- * Entries for the same team are grouped together before parsing.- *- * Format: `TEAM:QUEUE:TARGET[:PERCENTAGE],...`- *- * For queue-specific overrides with percentages < 1, the remainder is automatically- * filled from the team's `*` default.- *- * Example: `79155:*:kafka,79155:hog:postgres-v2:0.001` results in team 79155 routing- * 0.1% of hog jobs to postgres-v2 and 99.9% to kafka (remainder filled from team's `*`).- */-export function getProducerTeamMapping(stringMapping: string): CyclotronJobQueueTeamRouting {- if (!stringMapping) {- return {}- }-- // Group parts by team ID- const teamParts: Record<string, string[]> = {}- for (const part of stringMapping.split(',')) {- const [team, ...rest] = part.split(':')- if (!team || rest.length < 2) {- throw new Error(`Invalid team mapping: ${part} - expected format TEAM:QUEUE:TARGET[:PERCENTAGE]`)- }- if (!teamParts[team]) {- teamParts[team] = []- }- teamParts[team].push(rest.join(':'))- }-- const routing: CyclotronJobQueueTeamRouting = {}-- for (const [team, groupedParts] of Object.entries(teamParts)) {- const teamRouting = getProducerMapping(groupedParts.join(','))-- // Fill remainder for queues where percentages don't sum to 1,- // using the team's `*` default to fill the gap- for (const [queue, entries] of Object.entries(teamRouting)) {- if (queue === '*') {- continue- }- const sum = entries.reduce((acc, e) => acc + e.percentage, 0)- if (sum < 1 - PERCENTAGE_TOLERANCE) {- const fallbackEntries = teamRouting['*']- const remainder = 1 - sum- const fallbackSum = fallbackEntries.reduce((acc, e) => acc + e.percentage, 0)- for (const fallback of fallbackEntries) {- entries.push({- target: fallback.target,- percentage: (fallback.percentage / fallbackSum) * remainder,- })- }- }- }-- routing[team] = teamRouting- }-- return routing-}diff --git a/nodejs/src/cdp/services/job-queue/shared.test.ts b/nodejs/src/cdp/services/job-queue/shared.test.tsindex 5c6e55e18dee..b36a0b779824 100644--- a/nodejs/src/cdp/services/job-queue/shared.test.ts+++ b/nodejs/src/cdp/services/job-queue/shared.test.ts@@ -1,7 +1,8 @@import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../../_tests/examples'import { createHogExecutionGlobals, createHogFunction } from '../../_tests/fixtures'+import { CyclotronJobInvocationResult } from '../../types'import { createInvocation } from '../../utils/invocation-utils'-import { sanitizeInvocationForPersistence } from './shared'+import { createInvocationSanitizer, sanitizeInvocationForPersistence } from './shared'describe('sanitizeInvocationForPersistence', () => {const exampleHogFunction = createHogFunction({@@ -198,3 +199,76 @@ describe('sanitizeInvocationForPersistence', () => {}})})++describe('createInvocationSanitizer', () => {+ const exampleHogFunction = createHogFunction({+ name: 'Test hog function',+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const exampleGroups = {+ organization: {+ id: 'org-1',+ type: 'organization',+ index: 0,+ url: 'http://localhost:8000/groups/0/org-1',+ properties: { name: 'PostHog' },+ },+ }++ it('should strip groups from invocations', () => {+ const sanitizer = createInvocationSanitizer({ CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '' })+ const invocation = createInvocation(+ { ...createHogExecutionGlobals({ groups: exampleGroups }), inputs: {} },+ exampleHogFunction+ )++ const [sanitized] = sanitizer.sanitizeInvocations([invocation])+ expect(sanitized.state!.globals.groups).toBeUndefined()+ expect(sanitized.state!.globals.person).toBeDefined()+ })++ it('should strip person for configured teams', () => {+ const sanitizer = createInvocationSanitizer({ CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '2' })+ const invocation = createInvocation(+ { ...createHogExecutionGlobals({ groups: exampleGroups }), inputs: {} },+ { ...exampleHogFunction, team_id: 2 }+ )++ const [sanitized] = sanitizer.sanitizeInvocations([invocation])+ expect(sanitized.state!.globals.person).toBeUndefined()+ })++ it('should not strip person for non-configured teams', () => {+ const sanitizer = createInvocationSanitizer({ CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '99' })+ const invocation = createInvocation(+ { ...createHogExecutionGlobals({ groups: exampleGroups }), inputs: {} },+ { ...exampleHogFunction, team_id: 2 }+ )++ const [sanitized] = sanitizer.sanitizeInvocations([invocation])+ expect(sanitized.state!.globals.person).toBeDefined()+ })++ it('should sanitize results', () => {+ const sanitizer = createInvocationSanitizer({ CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '' })+ const invocation = createInvocation(+ { ...createHogExecutionGlobals({ groups: exampleGroups }), inputs: {} },+ exampleHogFunction+ )+ const result: CyclotronJobInvocationResult = {+ invocation,+ finished: false,+ error: null,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ }++ const [sanitized] = sanitizer.sanitizeResults([result])+ expect(sanitized.invocation.state!.globals.groups).toBeUndefined()+ })+})diff --git a/nodejs/src/cdp/services/job-queue/shared.ts b/nodejs/src/cdp/services/job-queue/shared.tsindex fd1eb29f9e10..182bc4f19b17 100644--- a/nodejs/src/cdp/services/job-queue/shared.ts+++ b/nodejs/src/cdp/services/job-queue/shared.ts@@ -1,6 +1,9 @@import { Histogram } from 'prom-client'-import { CyclotronJobInvocation } from '../../types'+import { buildIntegerMatcher } from '../../../config/config'+import { ValueMatcher } from '../../../types'+import { CdpConfig } from '../../config'+import { CyclotronJobInvocation, CyclotronJobInvocationResult } from '../../types'export const cdpJobSizeKb = new Histogram({name: 'cdp_cyclotron_job_size_kb',@@ -53,3 +56,31 @@ export function sanitizeInvocationForPersistence(},}}++/**+ * Creates a sanitizer that strips transient data before persisting.+ * Call once at construction time, use the returned functions on every queue operation.+ */+export function createInvocationSanitizer(config: Pick<CdpConfig, 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'>) {+ const stripPersonMatcher: ValueMatcher<number> = buildIntegerMatcher(+ config.CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS,+ true+ )++ return {+ sanitizeInvocations(invocations: CyclotronJobInvocation[]): CyclotronJobInvocation[] {+ return invocations.map((inv) =>+ sanitizeInvocationForPersistence(inv, { stripPerson: stripPersonMatcher(inv.teamId) })+ )+ },++ sanitizeResults(results: CyclotronJobInvocationResult[]): CyclotronJobInvocationResult[] {+ return results.map((result) => ({+ ...result,+ invocation: sanitizeInvocationForPersistence(result.invocation, {+ stripPerson: stripPersonMatcher(result.invocation.teamId),+ }),+ }))+ },+ }+}diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 6833e5c12859..01eb6bff5d08 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -1,3 +1,4 @@+import { createMockJobQueue } from '~/tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'import { mockFetch } from '~/tests/helpers/mocks/request.mock'@@ -43,7 +44,10 @@ describe('EmailTrackingService', () => {let server: ServerbeforeEach(async () => {- api = new CdpApi(hub, createCdpConsumerDeps(hub))+ api = new CdpApi(hub, createCdpConsumerDeps(hub), {+ hogQueue: createMockJobQueue(),+ hogflowQueue: createMockJobQueue(),+ })app = setupExpressApp()app.use('/', api.router())server = app.listen(0, () => {})diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 25f405419145..01ca32fb50a0 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -2,7 +2,7 @@* Workflows E2E tests through postgres-v2 (Cyclotron node DB).** These tests exercise the full hogflow lifecycle:- * event → CdpEventsConsumer → CyclotronJobQueue (produces to v2 DB)+ * event → CdpEventsConsumer → CyclotronJobQueuePostgresV2 (produces to v2 DB)* → CdpCyclotronWorkerHogFlow (polls v2 DB) → HogFlowExecutorService* → results written back to v2 DB → logs/metrics to Kafka*@@ -35,22 +35,21 @@ import { createHogExecutionGlobals, insertHogFunctionTemplate } from './_tests/fimport { insertHogFlow } from './_tests/fixtures-hogflows'import { CdpCyclotronWorkerHogFlow } from './consumers/cdp-cyclotron-worker-hogflow.consumer'import { CdpEventsConsumer } from './consumers/cdp-events.consumer'+import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'+import { CyclotronJobQueuePostgres } from './services/job-queue/job-queue-postgres'+import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'+import { JobQueue } from './services/job-queue/job-queue.interface'import { HogFunctionInvocationGlobals } from './types'-// Mock the v1 Cyclotron native addon — it crashes on import locally.-// We only use postgres-v2 in these tests so v1 is not needed.-jest.mock('@posthog/cyclotron', () => ({- CyclotronManager: jest.fn(),- CyclotronWorker: jest.fn(),-}))-const ActualKafkaProducerWrapper = jest.requireActual('../../src/kafka/producer').KafkaProducerWrapper-// Use the same env var as config.ts (line 210-211) so the cleanup pool and hub always target the same DB+// Use the same env vars as config.ts (lines 221-229) so cleanup pools and hub target the same DBsconst CYCLOTRON_NODE_DB_URL =process.env.CYCLOTRON_NODE_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'+const CYCLOTRON_DB_URL =+ process.env.CYCLOTRON_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron'-describe('Workflows E2E (postgres-v2)', () => {+describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)', (mode) => {jest.setTimeout(30000)let eventsConsumer: CdpEventsConsumer@@ -64,7 +63,9 @@ describe('Workflows E2E (postgres-v2)', () => {let cyclotronPool: PoolbeforeAll(() => {- cyclotronPool = new Pool({ connectionString: CYCLOTRON_NODE_DB_URL })+ cyclotronPool = new Pool({+ connectionString: mode === 'postgres-v2' ? CYCLOTRON_NODE_DB_URL : CYCLOTRON_DB_URL,+ })})afterAll(async () => {@@ -89,8 +90,6 @@ describe('Workflows E2E (postgres-v2)', () => {team = await getFirstTeam(hub.postgres)mockProducerObserver.resetKafkaProducer()- // Route hogflow to postgres-v2, everything else to kafka- hub.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = 'hogflow:postgres-v2,*:kafka'hub.CDP_CYCLOTRON_BATCH_DELAY_MS = 50hub.CDP_FETCH_RETRIES = 2hub.CDP_FETCH_BACKOFF_BASE_MS = 50@@ -111,16 +110,26 @@ describe('Workflows E2E (postgres-v2)', () => {const deps = createCdpConsumerDeps(hub, kafkaProducer)+ const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub)++ // Build the hogflow queue for the current mode+ let hogflowQueue: JobQueue+ if (mode === 'postgres-v2') {+ hogflowQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)+ } else {+ hogflowQueue = new CyclotronJobQueuePostgres(hub.CONSUMER_BATCH_SIZE, hub)+ }+// Events consumer — only start as producer (skip Kafka consumer connection).// We call processBatch() directly so the Kafka consumer is not needed.- eventsConsumer = new CdpEventsConsumer({ ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres-v2' }, deps)- await (eventsConsumer as any).cyclotronJobQueue.startAsProducer()+ eventsConsumer = new CdpEventsConsumer(hub, deps, {+ hogQueue: kafkaQueue,+ hogflowQueue,+ })+ await Promise.all([kafkaQueue.startAsProducer(), hogflowQueue.startAsProducer()])- // Start hogflow worker (consumer side — polls v2 DB)- hogflowWorker = new CdpCyclotronWorkerHogFlow(- { ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres-v2' },- deps- )+ // Start hogflow worker (consumer side — polls from the mode's backend)+ hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, deps, hogflowQueue)await hogflowWorker.start()mockFetch.mockResolvedValue({@@ -159,8 +168,15 @@ describe('Workflows E2E (postgres-v2)', () => {})}+ // v1 stores lifecycle in `state` (and vm payload in `vm_state`);+ // v2 stores lifecycle in `status` (and state payload in `state`).+ // Normalize so tests can use `.status` regardless of mode.+ const statusColumn = mode === 'postgres-v2' ? 'status' : 'state'+async function queryCyclotronJobs(): Promise<any[]> {- const result = await cyclotronPool.query('SELECT * FROM cyclotron_jobs ORDER BY created ASC')+ const result = await cyclotronPool.query(+ `SELECT *, ${statusColumn} AS status FROM cyclotron_jobs ORDER BY created ASC`+ )return result.rows}@@ -566,7 +582,7 @@ describe('Workflows E2E (postgres-v2)', () => {expect(mockFetch).not.toHaveBeenCalled()// Fast-forward: set the scheduled time to now so the worker picks it up- await cyclotronPool.query(`UPDATE cyclotron_jobs SET scheduled = NOW() WHERE status = 'available'`)+ await cyclotronPool.query(`UPDATE cyclotron_jobs SET scheduled = NOW() WHERE ${statusColumn} = 'available'`)await waitForExpect(() => {expect(mockFetch).toHaveBeenCalledTimes(1)diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 2c08d2a69d24..1ac62a40e1d8 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -21,6 +21,9 @@ import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'import { CdpProducerName } from './cdp/outputs/producers'import { CyclotronV2JanitorService } from './cdp/services/cyclotron-v2'import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-schedule.service'+import { CyclotronJobQueueKafka } from './cdp/services/job-queue/job-queue-kafka'+import { CyclotronJobQueuePostgres } from './cdp/services/job-queue/job-queue-postgres'+import { CyclotronJobQueuePostgresV2 } from './cdp/services/job-queue/job-queue-postgres-v2'import { EncryptedFields } from './cdp/utils/encryption-utils'import { defaultConfig } from './config/config'import { createIngestionRedisConnectionConfig, createPosthogRedisConnectionConfig } from './config/redis-pools'@@ -32,7 +35,6 @@ import { PluginServerService, PluginsServerConfig, RedisPool } from './types'import { ServerCommands } from './utils/commands'import { PostgresRouter } from './utils/db/postgres'import { createRedisPoolFromConfig } from './utils/db/redis'-import { isDevEnv } from './utils/env-utils'import { GeoIPService } from './utils/geoip'import { logger } from './utils/logger'import { PubSub } from './utils/pubsub'@@ -138,9 +140,16 @@ export class PluginServer implements NodeServer {)}+ // Create shared job queue backends — each consumer gets the one(s) it needs+ const kafkaQueue = new CyclotronJobQueueKafka(this.config.KAFKA_CLIENT_RACK, this.config)+ const postgresV2Queue = new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)+if (capabilities.cdpProcessedEvents) {serviceLoaders.push(async () => {- const consumer = new CdpEventsConsumer(this.config, cdpDeps!)+ const consumer = new CdpEventsConsumer(this.config, cdpDeps!, {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })await consumer.start()return consumer.service})@@ -148,7 +157,7 @@ export class PluginServer implements NodeServer {if (capabilities.cdpDataWarehouseEvents) {serviceLoaders.push(async () => {- const consumer = new CdpDatawarehouseEventsConsumer(this.config, cdpDeps!)+ const consumer = new CdpDatawarehouseEventsConsumer(this.config, cdpDeps!, kafkaQueue)await consumer.start()return consumer.service})@@ -156,7 +165,7 @@ export class PluginServer implements NodeServer {if (capabilities.cdpInternalEvents) {serviceLoaders.push(async () => {- const consumer = new CdpInternalEventsConsumer(this.config, cdpDeps!)+ const consumer = new CdpInternalEventsConsumer(this.config, cdpDeps!, kafkaQueue)await consumer.start()return consumer.service})@@ -164,7 +173,7 @@ export class PluginServer implements NodeServer {if (capabilities.cdpPersonUpdates) {serviceLoaders.push(async () => {- const consumer = new CdpPersonUpdatesConsumer(this.config, cdpDeps!)+ const consumer = new CdpPersonUpdatesConsumer(this.config, cdpDeps!, kafkaQueue)await consumer.start()return consumer.service})@@ -184,7 +193,10 @@ export class PluginServer implements NodeServer {if (capabilities.cdpApi) {serviceLoaders.push(async () => {- const api = new CdpApi(this.config, cdpDeps!)+ const api = new CdpApi(this.config, cdpDeps!, {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })this.lifecycle.expressApp.use('/', api.router())await api.start()return api.service@@ -192,23 +204,11 @@ export class PluginServer implements NodeServer {}if (capabilities.cdpCyclotronWorker) {- // Prod deploys one worker per consumer mode (separate pods). Dev runs- // all three in-process so a single launcher matches prod's fan-out —- // in particular, rerun re-enqueues land on postgres-v2 because- // `overwriteExisting: true` always routes there.- const consumerModes = isDevEnv()- ? (['kafka', 'postgres', 'postgres-v2'] as const)- : ([this.config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE] as const)- for (const mode of consumerModes) {- serviceLoaders.push(async () => {- const worker = new CdpCyclotronWorker(- { ...this.config, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: mode },- cdpDeps!- )- await worker.start()- return worker.service- })- }+ serviceLoaders.push(async () => {+ const worker = new CdpCyclotronWorker(this.config, cdpDeps!, kafkaQueue)+ await worker.start()+ return worker.service+ })}if (capabilities.cdpCyclotronV2Janitor) {@@ -234,25 +234,19 @@ export class PluginServer implements NodeServer {}if (capabilities.cdpCyclotronWorkerHogFlow) {- // Same dev-only fan-out as the worker above.- const consumerModes = isDevEnv()- ? (['kafka', 'postgres', 'postgres-v2'] as const)- : ([this.config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE] as const)- for (const mode of consumerModes) {- serviceLoaders.push(async () => {- const worker = new CdpCyclotronWorkerHogFlow(- { ...this.config, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: mode },- cdpDeps!- )- await worker.start()- return worker.service- })- }+ serviceLoaders.push(async () => {+ const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!, postgresV2Queue)+ await worker.start()+ return worker.service+ })}if (capabilities.cdpRerunWorker) {serviceLoaders.push(async () => {- const worker = new CdpRerunWorkerConsumer(this.config, cdpDeps!)+ const worker = new CdpRerunWorkerConsumer(this.config, cdpDeps!, {+ hog_function: kafkaQueue,+ hog_flow: postgresV2Queue,+ })await worker.start()return worker.service})@@ -261,10 +255,8 @@ export class PluginServer implements NodeServer {// Legacy postgres v1 drain for hogflow jobs — delete once cdp-cyclotron-worker-hogflows-pg-legacy is shut downif (capabilities.cdpCyclotronWorkerHogFlowLegacyPg) {serviceLoaders.push(async () => {- const worker = new CdpCyclotronWorkerHogFlow(- { ...this.config, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres' },- cdpDeps!- )+ const legacyQueue = new CyclotronJobQueuePostgres(this.config.CONSUMER_BATCH_SIZE, this.config)+ const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!, legacyQueue)await worker.start()return worker.service})@@ -287,7 +279,7 @@ export class PluginServer implements NodeServer {if (capabilities.cdpBatchHogFlow) {serviceLoaders.push(async () => {- const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!)+ const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!, postgresV2Queue)await consumer.start()return consumer.service})@@ -311,7 +303,7 @@ export class PluginServer implements NodeServer {if (capabilities.cdpBatchHogFlow) {serviceLoaders.push(async () => {- const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!)+ const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!, postgresV2Queue)await consumer.start()return consumer.service})diff --git a/nodejs/tests/helpers/mocks/job-queue.mock.ts b/nodejs/tests/helpers/mocks/job-queue.mock.tsnew file mode 100644index 000000000000..a3d1c73e3885--- /dev/null+++ b/nodejs/tests/helpers/mocks/job-queue.mock.ts@@ -0,0 +1,15 @@+import { JobQueue } from '../../../src/cdp/services/job-queue/job-queue.interface'++export function createMockJobQueue(): jest.Mocked<JobQueue> {+ return {+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ queueInvocationResults: jest.fn().mockResolvedValue(undefined),+ startAsProducer: jest.fn().mockResolvedValue(undefined),+ startAsConsumer: jest.fn().mockResolvedValue(undefined),+ stopConsumer: jest.fn().mockResolvedValue(undefined),+ stopProducer: jest.fn().mockResolvedValue(undefined),+ isHealthy: jest.fn(),+ dequeueInvocations: jest.fn().mockResolvedValue(undefined),+ cancelInvocations: jest.fn().mockResolvedValue(undefined),+ } as jest.Mocked<JobQueue>+}