: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
chore(cdp): remove the legacy Kafka batch hogflow consumer and routing (#67274)
Meikel Ratz2f5cd35f172f
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex cb45bce1be35..ff81b4073700 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -24,7 +24,6 @@ export const CAPABILITIES_CDP: PluginServerCapabilities = {/** CDP + Workflows - full CDP with HogFlow workflow automation */export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {...CAPABILITIES_CDP,- cdpBatchHogFlow: true,cdpCyclotronWorkerBatchResolve: true,cdpCyclotronWorkerHogFlow: true,cdpCyclotronWorkerEmail: true,@@ -175,10 +174,6 @@ export function getPluginServerCapabilities(return {errorTrackingIngestion: true,}- case PluginServerMode.cdp_batch_hogflow_requests:- return {- cdpBatchHogFlow: true,- }case PluginServerMode.cdp_cyclotron_worker_batch_resolve:return {cdpCyclotronWorkerBatchResolve: true,diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 2624a09f5a6e..c8fc5f9fca33 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -1,5 +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'import { Server } from 'http'@@ -774,14 +773,8 @@ describe('CDP API', () => {describe('batch hogflow invocations', () => {let batchHogFlow: HogFlow- let produceSpy: jest.SpyInstancebeforeEach(async () => {- // The batch hogflow route now goes through the outputs registry, which in- // tests routes every CDP producer slot at the shared `mockProducer`. Spying- // on its `produce` intercepts the produced message without reconstructing- // the api.- produceSpy = jest.spyOn(mockProducer, 'produce')batchHogFlow = await insertHogFlow({id: new UUIDT().toString(),name: 'test batch hog flow',@@ -806,10 +799,6 @@ describe('CDP API', () => {})})- afterEach(() => {- produceSpy.mockRestore()- })-it('errors if missing team', async () => {const nonExistentTeamId = new UUIDT().toString()const res = await supertest(app)@@ -855,73 +844,12 @@ describe('CDP API', () => {expect(res.body.error).toEqual('Only batch Workflows are supported for batch jobs')})- it('queues batch job request to kafka', async () => {- produceSpy.mockResolvedValue(undefined)-- const res = await supertest(app)- .post(`/api/projects/${batchHogFlow.team_id}/hog_flows/${batchHogFlow.id}/batch_invocations/job-123`)- .send({- filters: {- filter_test_accounts: true,- },- })-- expect(res.status).toEqual(200)- expect(res.body).toEqual({ status: 'queued' })- expect(produceSpy).toHaveBeenCalledWith({- topic: 'cdp_batch_hogflow_requests_test',- value: Buffer.from(- JSON.stringify({- teamId: batchHogFlow.team_id,- hogFlowId: batchHogFlow.id,- parentRunId: 'job-123',- filters: {- properties: (batchHogFlow as any).trigger.filters.properties,- filter_test_accounts: true,- },- })- ),- key: `${batchHogFlow.team_id}_${batchHogFlow.id}`,- })- })-- it('queues batch job with filters from hog flow config when not provided', async () => {- produceSpy.mockResolvedValue(undefined)-- const res = await supertest(app)- .post(`/api/projects/${batchHogFlow.team_id}/hog_flows/${batchHogFlow.id}/batch_invocations/job-456`)- .send({})-- expect(res.status).toEqual(200)- expect(res.body).toEqual({ status: 'queued' })- expect(produceSpy).toHaveBeenCalledWith({- topic: 'cdp_batch_hogflow_requests_test',- value: Buffer.from(- JSON.stringify({- teamId: batchHogFlow.team_id,- hogFlowId: batchHogFlow.id,- parentRunId: 'job-456',- filters: {- properties: (batchHogFlow as any).trigger.filters.properties,- filter_test_accounts: false,- },- })- ),- key: `${batchHogFlow.team_id}_${batchHogFlow.id}`,- })- })-- it('routes to the cyclotron resolver when CDP_BATCH_RESOLVER_ROUTING matches the team', async () => {- // Stub a producer in place of the real CyclotronV2Manager; assert- // it gets the right createJob payload (queue name, parentRunId,- // serialized state) without standing up a real cyclotron pool.+ it('queues batch job to the cyclotron resolver', async () => {const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')api['batchResolverProducer'] = {createJob: createJobMock,disconnect: jest.fn().mockResolvedValue(undefined),}- const originalMatcher = api['batchResolverRoutingMatcher']- api['batchResolverRoutingMatcher'] = () => truetry {const res = await supertest(app)@@ -937,9 +865,6 @@ describe('CDP API', () => {expect(res.status).toEqual(200)expect(res.body).toEqual({ status: 'queued' })- // Kafka path stays untouched- expect(produceSpy).not.toHaveBeenCalled()-expect(createJobMock).toHaveBeenCalledTimes(1)const arg = createJobMock.mock.calls[0][0]expect(arg).toMatchObject({@@ -954,6 +879,10 @@ describe('CDP API', () => {batchJobId: 'job-789',teamId: batchHogFlow.team_id,hogFlowId: batchHogFlow.id,+ filters: {+ properties: (batchHogFlow as any).trigger.filters.properties,+ filter_test_accounts: true,+ },maxAudienceSize: 1234,variables: { foo: 'bar' },cursor: null,@@ -961,7 +890,6 @@ describe('CDP API', () => {pagesProcessed: 0,})} finally {- api['batchResolverRoutingMatcher'] = originalMatcherapi['batchResolverProducer'] = null}})diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex a50395a49eeb..a9d287fb5067 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -2,7 +2,6 @@ import { DateTime } from 'luxon'import express from 'ultimate-express'import { ModifiedRequest } from '~/common/api/router'-import { buildIntegerMatcherWithPercentage } from '~/common/config/config'import { logger } from '~/common/utils/logger'import { UUID, UUIDT, delay } from '~/common/utils/utils'import { PluginEvent } from '~/plugin-scaffold'@@ -13,11 +12,10 @@ import {HealthCheckResultOk,PluginServerService,PluginsServerConfig,- ValueMatcher,} from '../types'import { getAsyncFunctionHandler, getRegisteredAsyncFunctionNames } from './async-function-registry'import './async-functions'-import { CdpOutputs, createCdpCoreServices } from './cdp-services'+import { createCdpCoreServices } from './cdp-services'import { CdpConsumerBaseDeps } from './consumers/cdp-base.consumer'import {CdpSourceWebhooksConsumer,@@ -25,7 +23,6 @@ import {SourceWebhookError,} from './consumers/cdp-source-webhooks.consumer'import { HogTransformerService, createHogTransformerService } from './hog-transformations/hog-transformer.service'-import { BATCH_HOGFLOW_REQUESTS_OUTPUT } from './outputs/outputs'import { RerunJobManager } from './rerun/rerun-job.manager'import { RerunRequest } from './rerun/rerun-job.types'import { BatchExportHogFunctionService, NotFoundError, ParseError } from './services/batch-export-hog-function.service'@@ -103,11 +100,9 @@ export class CdpApi {private hogflowQueue: JobQueueprivate emailTrackingService: EmailTrackingServiceprivate recipientTokensService: RecipientTokensService- private outputs: CdpOutputsprivate batchExportHogFunctionService: BatchExportHogFunctionServiceprivate groupsManager: GroupsManagerServiceprivate batchResolverProducer: CyclotronV2JobProducer | null- private batchResolverRoutingMatcher: ValueMatcher<number>constructor(private config: PluginsServerConfig,@@ -126,7 +121,6 @@ export class CdpApi {this.segmentDestinationExecutorService = services.segmentDestinationExecutorServicethis.hogWatcher = services.hogWatcherthis.invocationResultsService = services.invocationResultsService- this.outputs = services.outputs// API-only services. The hog-transformer's monitoring service reuses the same// resolved outputs registry as the core CDP services — no separate construction.@@ -157,7 +151,6 @@ export class CdpApi {this.invocationResultsService)this.batchResolverProducer = batchResolverProducer- this.batchResolverRoutingMatcher = buildIntegerMatcherWithPercentage(config.CDP_BATCH_RESOLVER_ROUTING)}public get service(): PluginServerService {@@ -781,49 +774,34 @@ export class CdpApi {const maxAudienceSize =typeof req.body.max_audience_size === 'number' ? req.body.max_audience_size : undefined- const batchHogFlowRequest = {+ if (!this.batchResolverProducer) {+ throw new Error('Batch resolver producer is not configured (missing CYCLOTRON_NODE_DATABASE_URL)')+ }++ const initialState: BatchResolverState = {+ batchJobId: parent_run_id,teamId: team.id,hogFlowId: hogFlow.id,- parentRunId: parent_run_id,filters: {properties: hogFlow.trigger.filters.properties || [],filter_test_accounts: req.body.filters?.filter_test_accounts || false,},- maxAudienceSize,- }-- if (this.batchResolverRoutingMatcher(team.id)) {- if (!this.batchResolverProducer) {- throw new Error('CDP_BATCH_RESOLVER_ROUTING matched team but no producer is configured')- }- const initialState: BatchResolverState = {- batchJobId: parent_run_id,- teamId: team.id,- hogFlowId: hogFlow.id,- filters: batchHogFlowRequest.filters,- variables: req.body.variables ?? {},- groupTypeIndex:- typeof req.body.group_type_index === 'number' ? req.body.group_type_index : undefined,- maxAudienceSize: maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,- cursor: null,- totalEnqueued: 0,- pagesProcessed: 0,- attempts: 0,- startedAt: new Date().toISOString(),- }- await this.batchResolverProducer.createJob({- teamId: team.id,- queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,- parentRunId: parent_run_id,- functionId: hogFlow.id,- state: serializeResolverState(initialState),- })- } else {- await this.outputs.produce(BATCH_HOGFLOW_REQUESTS_OUTPUT, {- value: Buffer.from(JSON.stringify(batchHogFlowRequest)),- key: `${team.id}_${hogFlow.id}`,- })- }+ variables: req.body.variables ?? {},+ groupTypeIndex: typeof req.body.group_type_index === 'number' ? req.body.group_type_index : undefined,+ maxAudienceSize: maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,+ cursor: null,+ totalEnqueued: 0,+ pagesProcessed: 0,+ attempts: 0,+ startedAt: new Date().toISOString(),+ }+ await this.batchResolverProducer.createJob({+ teamId: team.id,+ queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,+ parentRunId: parent_run_id,+ functionId: hogFlow.id,+ state: serializeResolverState(initialState),+ })res.json({ status: 'queued' })} catch (e) {diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 8964ea4c3fac..abe01cba716b 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -12,7 +12,6 @@ import type { CommonConfig } from '../common/config'import { InternalCaptureService } from '../common/services/internal-capture'import type { CdpConfig } from './config'import {- BatchHogflowRequestsOutput,PrecalculatedPersonPropertiesOutput,PrefilteredEventsOutput,WarehouseSourceWebhooksOutput,@@ -51,7 +50,6 @@ export type CdpOutput =| HogInvocationResultsOutput| PrefilteredEventsOutput| PrecalculatedPersonPropertiesOutput- | BatchHogflowRequestsOutput| WarehouseSourceWebhooksOutputexport type CdpOutputs = IngestionOutputs<CdpOutput>@@ -158,8 +156,6 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_PREFILTERED_EVENTS_PRODUCER'| 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC'| 'CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER'- | 'CDP_BATCH_HOGFLOW_REQUESTS_TOPIC'- | 'CDP_BATCH_HOGFLOW_REQUESTS_PRODUCER'| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC'| 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER'>diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 09ab253bee22..d7e212316bb1 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -1,6 +1,5 @@import {KAFKA_APP_METRICS_2,- KAFKA_CDP_BATCH_HOGFLOW_REQUESTS,KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_EVENTS_JSON,@@ -113,8 +112,6 @@ export type CdpConfig = ClickhouseConfig & {CDP_PREFILTERED_EVENTS_PRODUCER: CdpProducerNameCDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: stringCDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER: CdpProducerName- CDP_BATCH_HOGFLOW_REQUESTS_TOPIC: string- CDP_BATCH_HOGFLOW_REQUESTS_PRODUCER: CdpProducerNameCDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: stringCDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: CdpProducerName@@ -133,18 +130,8 @@ export type CdpConfig = ClickhouseConfig & {// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: boolean- CDP_BATCH_WORKFLOW_PRODUCER_BATCH_SIZE: numberCDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: number- // Per-team routing for postHogFlowBatchInvocation: teams matched here- // dispatch to a cyclotron resolver job (queue=hogflow_batch_resolve)- // instead of producing to the cdp_batch_hogflow_requests Kafka topic.- // Same string format as CDP_EMAIL_QUEUE_ROUTING — '' / '*' / '1,2' /- // '*:0.1' for percentage. The Kafka consumer path stays alive in- // parallel until this defaults to '*' everywhere and the legacy path- // is removed.- CDP_BATCH_RESOLVER_ROUTING: string-// Cyclotron Node (node postgres job queue)CYCLOTRON_NODE_MAX_CONNECTIONS: numberCYCLOTRON_NODE_IDLE_TIMEOUT_MS: number@@ -250,8 +237,6 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_PREFILTERED_EVENTS_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,- CDP_BATCH_HOGFLOW_REQUESTS_TOPIC: KAFKA_CDP_BATCH_HOGFLOW_REQUESTS,- CDP_BATCH_HOGFLOW_REQUESTS_PRODUCER: WARPSTREAM_CYCLOTRON_PRODUCER,CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC: KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER: WAREHOUSE_PRODUCER,@@ -277,9 +262,7 @@ export function getDefaultCdpConfig(): CdpConfig {// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: false,- CDP_BATCH_WORKFLOW_PRODUCER_BATCH_SIZE: 1,CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 5000,- CDP_BATCH_RESOLVER_ROUTING: '',// Cyclotron NodeCYCLOTRON_NODE_MAX_CONNECTIONS: 10,diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.tsdeleted file mode 100644index 8783b72ec185..000000000000--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts+++ /dev/null@@ -1,903 +0,0 @@-import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'--import { HogFlow } from '~/cdp/schema/hogflow'-import { closeHub, createHub } from '~/common/utils/db/hub'-import { UUIDT } from '~/common/utils/utils'--import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'-import { getFirstTeam, resetTestDatabase } from '../../../tests/helpers/sql'-import { Hub, Team } from '../../types'-import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'-import { createKafkaMessage } from '../_tests/fixtures'-import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'-import { BatchHogFlowRequest, CdpBatchHogFlowRequestsConsumer } from './cdp-batch-hogflow.consumer'--jest.setTimeout(1000)--describe('CdpBatchHogFlowRequestsConsumer', () => {- let processor: CdpBatchHogFlowRequestsConsumer- let hub: Hub- let team: Team- let mockQueueInvocations: jest.MockedFunction<any>-- const insertHogFlow = async (hogFlow: HogFlow) => {- const teamId = hogFlow.team_id ?? team.id- const item = await _insertHogFlow(hub.postgres, {- ...hogFlow,- team_id: teamId,- })- // Trigger the reload that django would do- processor['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [item.id])- return item- }-- beforeEach(async () => {- await resetTestDatabase()- hub = await createHub()- team = await getFirstTeam(hub.postgres)-- 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 only- processor['kafkaConsumer'] = {- connect: jest.fn(),- disconnect: jest.fn(),- isHealthy: jest.fn(),- } as any-- mockQueueInvocations = mockJobQueue.queueInvocations-- await processor.start()- })-- afterEach(async () => {- jest.setTimeout(10000)- await processor.stop()- await closeHub(hub)- })-- afterAll(() => {- jest.useRealTimers()- })-- describe('_parseKafkaBatch', () => {- it('should parse valid batch hog flow request messages', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- filter_test_accounts: false,- },- }-- const messages = [createKafkaMessage(batchRequest)]-- const result = await processor._parseKafkaBatch(messages)-- expect(result).toHaveLength(1)- expect(result[0]).toMatchObject({- batchHogFlowRequest: batchRequest,- team: expect.objectContaining({ id: team.id }),- hogFlow: expect.objectContaining({ id: hogFlow.id }),- })- })-- it('should filter out messages with missing hog flows', async () => {- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: 'non-existent-id',- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const messages = [createKafkaMessage(batchRequest)]-- const result = await processor._parseKafkaBatch(messages)-- expect(result).toHaveLength(0)- })-- it('should filter out messages with missing teams', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- const batchRequest: BatchHogFlowRequest = {- teamId: 999999, // Non-existent team- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const messages = [createKafkaMessage(batchRequest)]-- const result = await processor._parseKafkaBatch(messages)-- expect(result).toHaveLength(0)- })-- it('should handle malformed messages gracefully', async () => {- const messages = [- {- partition: 1,- topic: 'test',- offset: 0,- timestamp: Date.now(),- size: 1,- value: Buffer.from('invalid json'),- },- ]-- const result = await processor._parseKafkaBatch(messages as any)-- expect(result).toHaveLength(0)- })-- it('should filter out messages with draft hogflow status', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .withStatus('draft')- .build()- )-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const messages = [createKafkaMessage(batchRequest)]-- const result = await processor._parseKafkaBatch(messages)-- expect(result).toHaveLength(0)- })-- it('should filter out messages with archived hogflow status', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .withStatus('archived')- .build()- )-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const messages = [createKafkaMessage(batchRequest)]-- const result = await processor._parseKafkaBatch(messages)-- expect(result).toHaveLength(0)- })- })-- describe('createHogFlowInvocations', () => {- it('should return empty array if filters.properties is missing', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: {} as any,- },- })- .build()- )-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {},- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(0)- })-- it('should create invocations for matching persons', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Mock the batch person query service to return some persons- const mockGetBlastRadiusPersons = jest.fn().mockResolvedValue({- users_affected: ['person-1', 'person-2'],- cursor: null,- has_more: false,- })- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(2)- expect(result[0]).toMatchObject({- id: expect.any(String),- teamId: team.id,- functionId: hogFlow.id,- parentRunId: batchRequest.parentRunId,- queue: 'hogflow',- queuePriority: 1,- state: {- event: expect.objectContaining({- event: '$batch_hog_flow_invocation',- }),- actionStepCount: 0,- },- person: expect.objectContaining({- id: 'person-1',- }),- })- expect(result[1]).toMatchObject({- id: expect.any(String),- teamId: team.id,- parentRunId: batchRequest.parentRunId,- functionId: hogFlow.id,- queue: 'hogflow',- queuePriority: 1,- state: {- event: expect.objectContaining({- event: '$batch_hog_flow_invocation',- }),- actionStepCount: 0,- },- person: expect.objectContaining({- id: 'person-2',- }),- })-- expect(mockGetBlastRadiusPersons).toHaveBeenCalledWith(team, batchRequest.filters, undefined, null)- })-- it('should paginate through getBlastRadiusPersons until has_more is false', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- const mockGetBlastRadiusPersons = jest- .fn()- .mockResolvedValueOnce({- users_affected: ['person-1', 'person-2'],- cursor: 'cursor-1',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-3'],- cursor: null,- has_more: false,- })-- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- group_type_index: 5,- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(3)- expect(result.map((item) => (item as any).person?.id)).toEqual(['person-1', 'person-2', 'person-3'])-- expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(2)- expect(mockGetBlastRadiusPersons).toHaveBeenNthCalledWith(1, team, batchRequest.filters, 5, null)- expect(mockGetBlastRadiusPersons).toHaveBeenNthCalledWith(2, team, batchRequest.filters, 5, 'cursor-1')- })-- it('should stop processing when exceeding max audience size', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Set a low max audience size for testing- processor['config'] = { ...processor['config'], CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 3 }-- // Mock paginated responses that would exceed the limit- const mockGetBlastRadiusPersons = jest- .fn()- .mockResolvedValueOnce({- users_affected: ['person-1', 'person-2'],- cursor: 'cursor-1',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-3', 'person-4'],- cursor: 'cursor-2',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-5'],- cursor: null,- has_more: false,- })-- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- // Should have stopped after 2nd batch (4 total > 3 limit), not fetching the 3rd- expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(2)- // Only invocations from the first batch (before exceeding limit) should be included- expect(result).toHaveLength(2)- expect(result.map((item) => (item as any).person?.id)).toEqual(['person-1', 'person-2'])- })-- it('should let a request-level maxAudienceSize override the global config cap', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Global cap is low, but this team's elevated per-team limit rides on the request.- processor['config'] = { ...processor['config'], CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 3 }-- const mockGetBlastRadiusPersons = jest- .fn()- .mockResolvedValueOnce({- users_affected: ['person-1', 'person-2'],- cursor: 'cursor-1',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-3', 'person-4'],- cursor: 'cursor-2',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-5'],- cursor: null,- has_more: false,- })-- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- maxAudienceSize: 50000,- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- // All three pages are consumed despite the global cap of 3, and every person is queued.- expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(3)- expect(result).toHaveLength(5)- expect(result.map((item) => (item as any).person?.id)).toEqual([- 'person-1',- 'person-2',- 'person-3',- 'person-4',- 'person-5',- ])- })-- it('should fall back to the global config cap when the request has no maxAudienceSize', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- processor['config'] = { ...processor['config'], CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 3 }-- const mockGetBlastRadiusPersons = jest- .fn()- .mockResolvedValueOnce({- users_affected: ['person-1', 'person-2'],- cursor: 'cursor-1',- has_more: true,- })- .mockResolvedValueOnce({- users_affected: ['person-3', 'person-4'],- cursor: 'cursor-2',- has_more: true,- })-- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- // Stops after the 2nd page (4 > 3), same as the global-cap behavior.- expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(2)- expect(result).toHaveLength(2)- expect(result.map((item) => (item as any).person?.id)).toEqual(['person-1', 'person-2'])- })-- it('should include default variables from hogFlow', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Add variables to hogFlow- hogFlow.variables = [- { key: 'customVar1', type: 'string', label: 'Custom Var 1', default: 'defaultValue1' },- { key: 'customVar2', type: 'number', label: 'Custom Var 2', default: 42 },- { key: 'customVar3', type: 'string', label: 'Custom Var 3' }, // No default- ]-- // Mock the batch person query service- const mockGetBlastRadiusPersons = jest.fn().mockResolvedValue({- users_affected: ['person-1'],- })- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(1)- expect(result[0].state?.variables).toEqual({- customVar1: 'defaultValue1',- customVar2: 42,- customVar3: null,- })- })-- it('should record a workflow failure and not throw when audience query rejects', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- const queueAppMetricSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueAppMetric')- const queueLogsSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueLogs')-- // Simulate the Django endpoint failing (e.g. unsupported flag-typed property).- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = jest- .fn()- .mockRejectedValue(new Error('Failed to fetch blast radius persons: 500 Internal server error'))-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'flag-key', value: ['true'], operator: 'exact', type: 'flag' as any }],- },- }-- // Must resolve, not reject — the consumer should swallow the failure and continue.- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(0)-- expect(queueAppMetricSpy).toHaveBeenCalledWith(- expect.objectContaining({- team_id: hogFlow.team_id,- app_source_id: hogFlow.id,- instance_id: batchRequest.parentRunId,- metric_kind: 'failure',- metric_name: 'trigger_failed',- count: 1,- }),- 'hog_flow'- )-- expect(queueLogsSpy).toHaveBeenCalledWith(- [- expect.objectContaining({- team_id: hogFlow.team_id,- log_source: 'hog_flow',- log_source_id: batchRequest.parentRunId,- instance_id: batchRequest.parentRunId,- level: 'error',- message: expect.stringContaining('Failed to resolve batch audience'),- }),- ],- 'hog_flow'- )- })-- it('should record a missing_filters failure when filters.properties is empty', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: {} as any,- },- })- .build()- )-- const queueAppMetricSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueAppMetric')- const queueLogsSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueLogs')-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {},- }-- const result = await processor['createHogFlowInvocations']({- batchHogFlowRequest: batchRequest,- team,- hogFlow,- })-- expect(result).toHaveLength(0)- expect(queueAppMetricSpy).toHaveBeenCalledWith(- expect.objectContaining({- metric_kind: 'failure',- metric_name: 'trigger_failed',- instance_id: batchRequest.parentRunId,- }),- 'hog_flow'- )- expect(queueLogsSpy).toHaveBeenCalledWith(- [- expect.objectContaining({- log_source_id: batchRequest.parentRunId,- level: 'error',- message: expect.stringContaining('no property filters'),- }),- ],- 'hog_flow'- )- })- })-- describe('processBatch', () => {- it('should process batch and queue invocations', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Mock the batch person query service- const mockGetBlastRadiusPersons = jest.fn().mockResolvedValue({- users_affected: ['person-1'],- })- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const batchHogFlowRequestMessages = [- {- batchHogFlowRequest: batchRequest,- team,- hogFlow,- },- ]-- const { invocations, backgroundTask } = await processor['processBatch'](batchHogFlowRequestMessages)-- expect(invocations).toHaveLength(1)- expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)-- // Wait for background task to complete- await backgroundTask- })-- it('should handle empty batch', async () => {- const { invocations, backgroundTask } = await processor['processBatch']([])-- expect(invocations).toHaveLength(0)- expect(mockQueueInvocations).not.toHaveBeenCalled()-- await backgroundTask- })-- it('should process multiple requests in batch', async () => {- const hogFlow1 = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- const hogFlow2 = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Mock the batch person query service- const mockGetBlastRadiusPersons = jest.fn().mockResolvedValue({- users_affected: [{ person_id: 'person-1', distinct_id: 'distinct-1' }],- })- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest1: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow1.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const batchRequest2: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow2.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const batchHogFlowRequestMessages = [- { batchHogFlowRequest: batchRequest1, team, hogFlow: hogFlow1 },- { batchHogFlowRequest: batchRequest2, team, hogFlow: hogFlow2 },- ]-- const { invocations, backgroundTask } = await processor['processBatch'](batchHogFlowRequestMessages)-- expect(invocations).toHaveLength(2)- expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)- expect(invocations[0].functionId).toBe(hogFlow1.id)- expect(invocations[1].functionId).toBe(hogFlow2.id)-- await backgroundTask- })- })-- describe('integration', () => {- it('should process end-to-end from kafka messages to queued invocations', async () => {- const hogFlow = await insertHogFlow(- new FixtureHogFlowBuilder()- .withTeamId(team.id)- .withSimpleWorkflow({- trigger: {- type: 'batch',- filters: { properties: [] },- },- })- .build()- )-- // Mock the batch person query service- const mockGetBlastRadiusPersons = jest.fn().mockResolvedValue({- users_affected: ['distinct-1', 'distinct-2'],- })- processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons-- const batchRequest: BatchHogFlowRequest = {- teamId: team.id,- hogFlowId: hogFlow.id,- parentRunId: new UUIDT().toString(),- filters: {- properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],- },- }-- const messages = [createKafkaMessage(batchRequest)]-- // Parse Kafka messages- const parsedMessages = await processor._parseKafkaBatch(messages)- expect(parsedMessages).toHaveLength(1)-- // Process the batch- const { invocations, backgroundTask } = await processor['processBatch'](parsedMessages)-- expect(invocations).toHaveLength(2)- expect(invocations[0]).toMatchObject({- teamId: team.id,- functionId: hogFlow.id,- queue: 'hogflow',- person: {- id: 'distinct-1',- },- })- expect(invocations[1]).toMatchObject({- teamId: team.id,- functionId: hogFlow.id,- queue: 'hogflow',- person: {- id: 'distinct-2',- },- })-- expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)-- await backgroundTask- })- })-})diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.tsdeleted file mode 100644index 6d518ebe3654..000000000000--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts+++ /dev/null@@ -1,372 +0,0 @@-import { Message } from 'node-rdkafka'--import { HogFlow } from '~/cdp/schema/hogflow'-import { KAFKA_CDP_BATCH_HOGFLOW_REQUESTS } from '~/common/config/kafka-topics'-import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'-import { InternalFetchService } from '~/common/services/internal-fetch'-import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'-import { parseJSON } from '~/common/utils/json-parse'-import { logger, serializeError } from '~/common/utils/logger'-import { captureException } from '~/common/utils/posthog'-import { UUIDT } from '~/common/utils/utils'--import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'-import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'-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'-import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { counterBatchHogFlowTriggerFailed, counterParseError } from './metrics'--export interface BatchHogFlowRequest {- teamId: number- hogFlowId: HogFlow['id']- parentRunId: string- filters: Pick<HogFunctionFilters, 'properties' | 'filter_test_accounts'>- group_type_index?: number- // Per-team audience cap resolved on the Django side (HOGFLOW_BATCH_TRIGGER_LIMIT). When absent,- // we fall back to the global CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE config default.- maxAudienceSize?: number-}--export interface BatchHogFlowRequestMessage {- batchHogFlowRequest: BatchHogFlowRequest- team: Team- hogFlow: HogFlow-}--export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServerConfig> {- protected name = 'CdpBatchHogFlowRequestsConsumer'- private cyclotronJobQueue: JobQueue- protected kafkaConsumer: KafkaConsumerInterface- private hogFlowBatchPersonQueryService: HogFlowBatchPersonQueryService-- constructor(- 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 = jobQueue- this.kafkaConsumer = createKafkaConsumer({ groupId, topic })- this.hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(- new InternalFetchService(config.INTERNAL_API_BASE_URL, config.INTERNAL_API_SECRET)- )- }-- private createHogFlowInvocation({- parentRunId,- hogFlow,- team,- personId,- defaultVariables,- }: {- parentRunId: string- hogFlow: HogFlow- team: Team- personId: string- defaultVariables: Record<string, any>- }): CyclotronJobInvocation {- const invocationGlobals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({- team: team,- personId,- siteUrl: this.config.SITE_URL,- })-- const filterGlobals = convertToHogFunctionFilterGlobal(invocationGlobals)-- const invocation = {- id: new UUIDT().toString(),- state: {- event: invocationGlobals.event,- personId,- actionStepCount: 0,- variables: defaultVariables,- },- teamId: hogFlow.team_id,- functionId: hogFlow.id,- parentRunId,- hogFlow,- person: invocationGlobals.person,- filterGlobals,- queue: 'hogflow' as const,- queuePriority: 1,- }- return invocation- }-- /**- * Finds all matching persons for the given globals.- * Filters them based on the hogflow's masking configs- */- @instrumented('cdpProducer.generateBatch.queueMatchingPersons')- protected async createHogFlowInvocations(- batchHogFlowRequestMessage: BatchHogFlowRequestMessage- ): Promise<CyclotronJobInvocation[]> {- const { batchHogFlowRequest, team, hogFlow } = batchHogFlowRequestMessage- const { filters } = batchHogFlowRequest-- if (!filters.properties || !filters.properties.length) {- logger.error('Batch HogFlow request missing property filters', { batchHogFlowRequest })- this.recordBatchTriggerFailure(- batchHogFlowRequestMessage,- 'missing_filters',- 'Batch trigger has no property filters configured.'- )- return []- }-- // Build default variables from hogFlow- const defaultVariables =- hogFlow.variables?.reduce(- (acc, variable) => {- acc[variable.key] = variable.default || null- return acc- },- {} as Record<string, any>- ) || {}-- const allInvocations: CyclotronJobInvocation[] = []- let cursor: string | null = null- let totalPersonsProcessed = 0- const maxAudienceSize = batchHogFlowRequest.maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE-- try {- // Fetch persons in batches using cursor-based pagination- do {- const blastRadiusPersons = await instrumentFn(- 'cdpProducer.generateBatch.queueMatchingPersons.getBlastRadiusPersons',- async () => {- return await this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(- team,- filters,- batchHogFlowRequest.group_type_index,- cursor- )- }- )-- const batchPersonsCount = blastRadiusPersons.users_affected.length- totalPersonsProcessed += batchPersonsCount-- if (totalPersonsProcessed > maxAudienceSize) {- logger.warn(- '⚠️',- `Batch HogFlow run ${batchHogFlowRequest.parentRunId} has exceeded the maximum audience size of ${maxAudienceSize}. Stopping further processing.`,- { totalPersonsProcessed, batchHogFlowRequest }- )- break- }-- logger.info(- '📝',- `Fetched ${batchPersonsCount} persons (${totalPersonsProcessed} total) for batch HogFlow run ${batchHogFlowRequest.parentRunId}`- )-- // Create invocations for this batch of persons- const batchInvocations = blastRadiusPersons.users_affected.map((personId) =>- this.createHogFlowInvocation({- parentRunId: batchHogFlowRequest.parentRunId,- hogFlow,- team,- personId,- defaultVariables,- })- )-- allInvocations.push(...batchInvocations)-- // Update cursor for next iteration- cursor = blastRadiusPersons.cursor-- // Continue if there are more persons to fetch- if (!blastRadiusPersons.has_more) {- break- }- } while (cursor)- } catch (error) {- // Audience resolution failed (e.g. unsupported filter property like a feature flag in person scope).- // Record a workflow-level failure so the run is observable in logs/metrics, then drop the batch- // instead of crashing the consumer and re-processing the same poison message in a tight loop.- const message = error instanceof Error ? error.message : String(error)- logger.error('🔴', 'Failed to resolve audience for batch HogFlow run, skipping batch', {- error: serializeError(error),- hogFlowId: hogFlow.id,- teamId: team.id,- parentRunId: batchHogFlowRequest.parentRunId,- })- captureException(error, {- tags: { hogFlowId: hogFlow.id, parentRunId: batchHogFlowRequest.parentRunId },- })- this.recordBatchTriggerFailure(- batchHogFlowRequestMessage,- 'audience_query_failed',- `Failed to resolve batch audience: ${message}`- )- return []- }-- logger.info(- '✅',- `Created ${allInvocations.length} invocations for batch HogFlow run ${batchHogFlowRequest.parentRunId}`- )-- return allInvocations- }-- private recordBatchTriggerFailure(- batchHogFlowRequestMessage: BatchHogFlowRequestMessage,- reason: 'missing_filters' | 'audience_query_failed',- userMessage: string- ): void {- const { batchHogFlowRequest, hogFlow } = batchHogFlowRequestMessage-- counterBatchHogFlowTriggerFailed.labels({ hog_flow_id: hogFlow.id, reason }).inc()-- this.hogFunctionMonitoringService.queueAppMetric(- {- team_id: hogFlow.team_id,- app_source_id: hogFlow.id,- instance_id: batchHogFlowRequest.parentRunId,- metric_kind: 'failure',- metric_name: 'trigger_failed',- count: 1,- },- 'hog_flow'- )-- this.hogFunctionMonitoringService.queueLogs(- [- {- team_id: hogFlow.team_id,- log_source: 'hog_flow',- log_source_id: batchHogFlowRequest.parentRunId,- instance_id: batchHogFlowRequest.parentRunId,- ...logEntry('error', userMessage),- },- ],- 'hog_flow'- )- }-- private async processBatchHogFlowRequest(- batchHogFlowRequests: BatchHogFlowRequestMessage[]- ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {- if (batchHogFlowRequests.length > 1) {- logger.warn(- '🔁',- `Processing multiple ${batchHogFlowRequests.length} hog flow requests. This is NOT recommended due to potential fanout. Batch size is set by CDP_BATCH_WORKFLOW_PRODUCER_BATCH_SIZE`- )- }-- const invocationsToBeQueued = [- ...(- await Promise.all(batchHogFlowRequests.map((request) => this.createHogFlowInvocations(request)))- ).flat(),- ]-- logger.info('📝', `Created ${invocationsToBeQueued.length} hog flow invocations to be queued`)-- return {- // This is all IO so we can set them off in the background and start processing the next batch- backgroundTask: Promise.all([- this.cyclotronJobQueue.queueInvocations(invocationsToBeQueued),- this.hogFunctionMonitoringService.flush().catch((err) => {- captureException(err)- logger.error('🔴', 'Error producing queued messages for monitoring', { err })- }),- ]),- invocations: invocationsToBeQueued,- }- }-- private async processBatch(- batchHogFlowRequests: BatchHogFlowRequestMessage[]- ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {- if (!batchHogFlowRequests.length) {- return { backgroundTask: Promise.resolve(), invocations: [] }- }-- return await instrumentFn('cdpConsumer.processBatchHogFlowRequest', async () => {- return await this.processBatchHogFlowRequest(batchHogFlowRequests)- })- }-- @instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')- public async _parseKafkaBatch(messages: Message[]): Promise<BatchHogFlowRequestMessage[]> {- const batchHogFlowRequests: BatchHogFlowRequestMessage[] = []-- await Promise.all(- messages.map(async (message) => {- try {- const batchHogFlowRequest = parseJSON(message.value!.toString()) as BatchHogFlowRequest-- const [teamHogFlow, team] = await Promise.all([- this.hogFlowManager.getHogFlow(batchHogFlowRequest.hogFlowId),- this.deps.teamManager.getTeam(batchHogFlowRequest.teamId),- ])-- if (!teamHogFlow || !team) {- logger.error('Batch HogFlow request references missing team or hogflow', {- batchHogFlowRequest,- })- return- }-- if (teamHogFlow.status !== 'active') {- logger.info('Skipping inactive HogFlow for batch request', { batchHogFlowRequest })- return- }-- batchHogFlowRequests.push({- batchHogFlowRequest,- team,- hogFlow: teamHogFlow,- })- } catch (e) {- logger.error('Error parsing message', e)- counterParseError.labels({ error: e.message }).inc()- }- })- )-- return batchHogFlowRequests- }-- public override async start(): Promise<void> {- await super.start()- // Make sure we are ready to produce to cyclotron first- await this.cyclotronJobQueue.startAsProducer()- // Start consuming messages- await this.kafkaConsumer.connect(async (messages) => {- logger.info('🔁', `${this.name} - handling batch`, {- size: messages.length,- })-- return await instrumentFn('cdpConsumer.handleEachBatch', async () => {- const batchHogFlowRequestMessages = await this._parseKafkaBatch(messages)- const { backgroundTask } = await this.processBatch(batchHogFlowRequestMessages)-- return { backgroundTask }- })- })- }-- public override async stop(): Promise<void> {- logger.info('💤', 'Stopping consumer...')- await this.kafkaConsumer.disconnect()- logger.info('💤', 'Stopping cyclotron job queue...')- await this.cyclotronJobQueue.stopProducer()- logger.info('💤', 'Stopping consumer...')- // IMPORTANT: super always comes last- await super.stop()- logger.info('💤', 'Consumer stopped!')- }-- public isHealthy(): HealthCheckResult {- return this.kafkaConsumer.isHealthy()- }-}diff --git a/nodejs/src/cdp/outputs/outputs.ts b/nodejs/src/cdp/outputs/outputs.tsindex ef47965b4979..87baf85c3af4 100644--- a/nodejs/src/cdp/outputs/outputs.ts+++ b/nodejs/src/cdp/outputs/outputs.ts@@ -13,8 +13,5 @@ export type PrefilteredEventsOutput = typeof PREFILTERED_EVENTS_OUTPUTexport const PRECALCULATED_PERSON_PROPERTIES_OUTPUT = 'precalculated_person_properties' as constexport type PrecalculatedPersonPropertiesOutput = typeof PRECALCULATED_PERSON_PROPERTIES_OUTPUT-export const BATCH_HOGFLOW_REQUESTS_OUTPUT = 'batch_hogflow_requests' as const-export type BatchHogflowRequestsOutput = typeof BATCH_HOGFLOW_REQUESTS_OUTPUT-export const WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT = 'warehouse_source_webhooks' as constexport type WarehouseSourceWebhooksOutput = typeof WAREHOUSE_SOURCE_WEBHOOKS_OUTPUTdiff --git a/nodejs/src/cdp/outputs/registry.ts b/nodejs/src/cdp/outputs/registry.tsindex 5dcde6f48725..c3e628401cac 100644--- a/nodejs/src/cdp/outputs/registry.ts+++ b/nodejs/src/cdp/outputs/registry.ts@@ -2,7 +2,6 @@ import { APP_METRICS_OUTPUT, HOG_INVOCATION_RESULTS_OUTPUT, LOG_ENTRIES_OUTPUT }import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'import {- BATCH_HOGFLOW_REQUESTS_OUTPUT,PRECALCULATED_PERSON_PROPERTIES_OUTPUT,PREFILTERED_EVENTS_OUTPUT,WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT,@@ -18,7 +17,6 @@ import {* `clickhouse_app_metrics2` schema).* - `PREFILTERED_EVENTS_OUTPUT` + `PRECALCULATED_PERSON_PROPERTIES_OUTPUT` —* precalculated-filters consumer writes to ClickHouse.- * - `BATCH_HOGFLOW_REQUESTS_OUTPUT` — batch hogflow invocation queue.* - `WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT` — warehouse source webhook payloads.*/export function createCdpOutputsRegistry() {@@ -43,10 +41,6 @@ export function createCdpOutputsRegistry() {topicKey: 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC',producerKey: 'CDP_PRECALCULATED_PERSON_PROPERTIES_PRODUCER',})- .register(BATCH_HOGFLOW_REQUESTS_OUTPUT, {- topicKey: 'CDP_BATCH_HOGFLOW_REQUESTS_TOPIC',- producerKey: 'CDP_BATCH_HOGFLOW_REQUESTS_PRODUCER',- }).register(WAREHOUSE_SOURCE_WEBHOOKS_OUTPUT, {topicKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_TOPIC',producerKey: 'CDP_WAREHOUSE_SOURCE_WEBHOOKS_PRODUCER',diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 51a3bea16990..9f8e50e5e39f 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -287,8 +287,8 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)/*** Construct and enqueue a batch-shaped CyclotronJobInvocation directly, mimicking what- * CdpBatchHogFlowRequestsConsumer.createHogFlowInvocation would produce. Skips the- * blast-radius API call so tests don't need to stand up the Django side.+ * the batch resolver's buildHogFlowInvocation would produce. Skips the blast-radius API+ * call so tests don't need to stand up the Django side.*/async function triggerBatchWorkflow(hogFlow: HogFlow, personUuid: string): Promise<void> {const invocationGlobals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({@@ -2677,10 +2677,8 @@ describe('Workflows E2E (email queue)', () => {* E2E for the batch resolver dispatch path through the cdp-api HTTP boundary.** Goes through real express + supertest, real CdpApi, real cyclotron-node- * Postgres. Verifies that POST `/batch_invocations/<id>` with the- * `CDP_BATCH_RESOLVER_ROUTING` matching the team creates a resolver- * cyclotron job pointing at the right queue with the right state. When the- * routing matcher excludes the team, the legacy Kafka path takes over.+ * Postgres. Verifies that POST `/batch_invocations/<id>` creates a resolver+ * cyclotron job pointing at the right queue with the right state.** The deep state-machine paths (page execution, terminal write, truncation,* Django down → resolver parks) are covered by the integration tests in@@ -2723,7 +2721,6 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {hub = await createHub({SITE_URL: 'http://localhost:8000',- CDP_BATCH_RESOLVER_ROUTING: '*',})const { createMockJobQueue } = require('../../tests/helpers/mocks/job-queue.mock')@@ -2753,7 +2750,6 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {await resetTestDatabase()await cyclotronPool.query(`DELETE FROM cyclotron_jobs`)team = await getFirstTeam(hub.postgres)- api['batchResolverRoutingMatcher'] = () => trueresolverWorker = undefined})@@ -2856,26 +2852,6 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {expect(state.pendingTerminal).toBeUndefined()})- it('POST /batch_invocations with no routing match falls back to the legacy Kafka path', async () => {- api['batchResolverRoutingMatcher'] = () => false-- const flow = await insertActiveBatchFlow()- const parentRunId = new UUIDT().toString()-- const response = await supertest(app)- .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)- .send({ filters: { filter_test_accounts: false } })- .expect(200)-- expect(response.body).toEqual({ status: 'queued' })-- const rows = await cyclotronPool.query(- `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,- [parentRunId]- )- expect(rows.rows).toHaveLength(0)- })-it('rejects with 400 when the workflow is not a batch trigger', async () => {const flow = new FixtureHogFlowBuilder().withTeamId(team.id)diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 2a77b99d0f4b..c8998bcdda73 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -42,7 +42,6 @@ export enum PluginServerMode {ingestion_logs = 'ingestion-logs',ingestion_error_tracking = 'ingestion-errortracking',ingestion_metrics = 'ingestion-metrics',- cdp_batch_hogflow_requests = 'cdp-batch-hogflow-requests',cdp_cyclotron_worker_batch_resolve = 'cdp-cyclotron-worker-batch-resolve',cdp_cyclotron_v2_janitor = 'cdp-cyclotron-v2-janitor',cdp_rerun_worker = 'cdp-rerun-worker',diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex 2f2b57a08ca3..ff6ef33c44ce 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -61,7 +61,6 @@ export const KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES = `${prefix}clexport const KAFKA_COHORT_MEMBERSHIP_CHANGED = `${prefix}cohort_membership_changed${suffix}`// Cross-partition merge protocol trigger consumed by the cohort-stream-processor (Rust).export const KAFKA_PERSON_MERGE_EVENTS = `${prefix}person_merge_events${suffix}`-export const KAFKA_CDP_BATCH_HOGFLOW_REQUESTS = `${prefix}cdp_batch_hogflow_requests${suffix}`// Error tracking topicsexport const KAFKA_ERROR_TRACKING_INGESTION = `${prefix}ingestion-errortracking-main${suffix}` // Partition count varies by envdiff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex e50062831fb1..3d0a84421a00 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -23,7 +23,6 @@ import { startEvaluationScheduler } from './ai-observability/evaluation-scheduleimport { getPluginServerCapabilities } from './capabilities'import { CdpApi } from './cdp/cdp-api'import { CdpConsumerBaseDeps } from './cdp/consumers/cdp-base.consumer'-import { CdpBatchHogFlowRequestsConsumer } from './cdp/consumers/cdp-batch-hogflow.consumer'import { CdpCohortMembershipConsumer } from './cdp/consumers/cdp-cohort-membership.consumer'import { CdpCyclotronWorkerBatchResolve } from './cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer'import { CdpCyclotronWorkerEmail } from './cdp/consumers/cdp-cyclotron-worker-email.consumer'@@ -103,7 +102,6 @@ export class PluginServer implements NodeServer {capabilities.cdpCyclotronWorkerEmailLegacyPg ||capabilities.cdpPrecalculatedFilters ||capabilities.cdpCohortMembership ||- capabilities.cdpBatchHogFlow ||capabilities.cdpCyclotronWorkerBatchResolve ||capabilities.cdpHogflowSubscriptionMatcher ||capabilities.cdpRerunWorker@@ -208,9 +206,10 @@ export class PluginServer implements NodeServer {if (capabilities.cdpApi) {serviceLoaders.push(async () => {- // Only wire a batch-resolver producer when the cyclotron-node DB- // is configured; otherwise leave it null (flag-off path uses- // Kafka and doesn't need a producer).+ // Batch triggers require the cyclotron-node DB; when it isn't+ // configured (typically local dev), the null producer causes+ // the batch-invocation endpoint to throw on request rather+ // than at boot.const batchResolverProducer = this.config.CYCLOTRON_NODE_DATABASE_URL? new CyclotronV2Manager({pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL, maxConnections: 5 },@@ -347,14 +346,6 @@ export class PluginServer implements NodeServer {return Promise.resolve(serverCommands.service)})- if (capabilities.cdpBatchHogFlow) {- serviceLoaders.push(async () => {- const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!, postgresV2Queue)- await consumer.start()- return consumer.service- })- }-if (capabilities.cdpPrecalculatedFilters) {serviceLoaders.push(async () => {const worker = new CdpPrecalculatedFiltersConsumer(this.config, cdpDeps!)@@ -371,14 +362,6 @@ export class PluginServer implements NodeServer {})}- if (capabilities.cdpBatchHogFlow) {- serviceLoaders.push(async () => {- const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!, postgresV2Queue)- await consumer.start()- return consumer.service- })- }-if (capabilities.cdpHogflowSubscriptionMatcher) {serviceLoaders.push(async () => {const consumer = new CdpHogflowSubscriptionMatcherConsumer(this.config, cdpDeps!)diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex 44690d47d441..1c30d3afa778 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -142,7 +142,6 @@ export interface PluginServerCapabilities {cdpPersonUpdates?: booleancdpInternalEvents?: booleancdpLegacyOnEvent?: boolean- cdpBatchHogFlow?: booleancdpCyclotronWorkerBatchResolve?: booleancdpCyclotronWorker?: booleancdpCyclotronWorkerHogFlow?: boolean