Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp-email): cyclotron-based batch resolver (#65864)

Meikel Ratz08283f61a4af
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index f80e63133970..b2ccdc309c41 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -25,6 +25,7 @@ export const CAPABILITIES_CDP: PluginServerCapabilities = {
export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {
...CAPABILITIES_CDP,
cdpBatchHogFlow: true,
+ cdpCyclotronWorkerBatchResolve: true,
cdpCyclotronWorkerHogFlow: true,
cdpCyclotronWorkerEmail: true,
cdpCyclotronV2Janitor: isDevEnv(),
@@ -178,6 +179,10 @@ export function getPluginServerCapabilities(
return {
cdpBatchHogFlow: true,
}
+ case PluginServerMode.cdp_cyclotron_worker_batch_resolve:
+ return {
+ cdpCyclotronWorkerBatchResolve: true,
+ }
case PluginServerMode.cdp_data_warehouse_events:
return {
cdpDataWarehouseEvents: true,
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index 2a66330b0fb9..2624a09f5a6e 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -11,6 +11,7 @@ import { setupExpressApp } from '~/common/api/router'
import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { closeHub, createHub } from '~/common/utils/db/hub'
+import { parseJSON } from '~/common/utils/json-parse'
import { UUIDT } from '~/common/utils/utils'
import { createCdpConsumerDeps } from '../../tests/helpers/cdp'
@@ -909,6 +910,61 @@ describe('CDP API', () => {
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.
+ const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
+ api['batchResolverProducer'] = {
+ createJob: createJobMock,
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ }
+ const originalMatcher = api['batchResolverRoutingMatcher']
+ api['batchResolverRoutingMatcher'] = () => true
+
+ try {
+ const res = await supertest(app)
+ .post(
+ `/api/projects/${batchHogFlow.team_id}/hog_flows/${batchHogFlow.id}/batch_invocations/job-789`
+ )
+ .send({
+ filters: { filter_test_accounts: true },
+ max_audience_size: 1234,
+ variables: { foo: 'bar' },
+ })
+
+ 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({
+ teamId: batchHogFlow.team_id,
+ queueName: 'hogflow_batch_resolve',
+ parentRunId: 'job-789',
+ functionId: batchHogFlow.id,
+ })
+ expect(arg.state).toBeInstanceOf(Buffer)
+ const state = parseJSON((arg.state as Buffer).toString('utf-8')) as Record<string, unknown>
+ expect(state).toMatchObject({
+ batchJobId: 'job-789',
+ teamId: batchHogFlow.team_id,
+ hogFlowId: batchHogFlow.id,
+ maxAudienceSize: 1234,
+ variables: { foo: 'bar' },
+ cursor: null,
+ totalEnqueued: 0,
+ pagesProcessed: 0,
+ })
+ } finally {
+ api['batchResolverRoutingMatcher'] = originalMatcher
+ api['batchResolverProducer'] = null
+ }
+ })
})
describe('scheduled hogflow invocations', () => {
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index d3e98acbdbf0..a50395a49eeb 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -2,6 +2,7 @@ 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'
@@ -12,6 +13,7 @@ import {
HealthCheckResultOk,
PluginServerService,
PluginsServerConfig,
+ ValueMatcher,
} from '../types'
import { getAsyncFunctionHandler, getRegisteredAsyncFunctionNames } from './async-function-registry'
import './async-functions'
@@ -27,7 +29,13 @@ 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'
+import type { CyclotronV2JobProducer } from './services/cyclotron-v2'
import { HogExecutorExecuteAsyncOptions, HogExecutorService, MAX_ASYNC_STEPS } from './services/hog-executor.service'
+import {
+ BatchResolverState,
+ HOGFLOW_BATCH_RESOLVE_QUEUE,
+ serializeResolverState,
+} from './services/hogflows/batch-resolver.types'
import { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'
import { InvocationResultsService } from './services/invocation-results.service'
@@ -98,11 +106,14 @@ export class CdpApi {
private outputs: CdpOutputs
private batchExportHogFunctionService: BatchExportHogFunctionService
private groupsManager: GroupsManagerService
+ private batchResolverProducer: CyclotronV2JobProducer | null
+ private batchResolverRoutingMatcher: ValueMatcher<number>
constructor(
private config: PluginsServerConfig,
private deps: CdpApiDeps,
- jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }
+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue },
+ batchResolverProducer: CyclotronV2JobProducer | null = null
) {
const services = createCdpCoreServices(config, deps, 'cdp-api-redis')
@@ -145,6 +156,8 @@ export class CdpApi {
this.hogWatcher,
this.invocationResultsService
)
+ this.batchResolverProducer = batchResolverProducer
+ this.batchResolverRoutingMatcher = buildIntegerMatcherWithPercentage(config.CDP_BATCH_RESOLVER_ROUTING)
}
public get service(): PluginServerService {
@@ -779,10 +792,38 @@ export class CdpApi {
maxAudienceSize,
}
- await this.outputs.produce(BATCH_HOGFLOW_REQUESTS_OUTPUT, {
- value: Buffer.from(JSON.stringify(batchHogFlowRequest)),
- key: `${team.id}_${hogFlow.id}`,
- })
+ 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}`,
+ })
+ }
res.json({ status: 'queued' })
} catch (e) {
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 23bff73cc42c..09ab253bee22 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -136,6 +136,15 @@ export type CdpConfig = ClickhouseConfig & {
CDP_BATCH_WORKFLOW_PRODUCER_BATCH_SIZE: number
CDP_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: number
CYCLOTRON_NODE_IDLE_TIMEOUT_MS: number
@@ -270,6 +279,7 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_BATCH_WORKFLOW_PRODUCER_BATCH_SIZE: 1,
CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 5000,
+ CDP_BATCH_RESOLVER_ROUTING: '',
// Cyclotron Node
CYCLOTRON_NODE_MAX_CONNECTIONS: 10,
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
new file mode 100644
index 000000000000..85c174491e6f
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
@@ -0,0 +1,449 @@
+import { DateTime } from 'luxon'
+import { Counter } from 'prom-client'
+
+import { InternalFetchService } from '~/common/services/internal-fetch'
+import { instrumentFn } from '~/common/tracing/tracing-utils'
+import { logger, serializeError } from '~/common/utils/logger'
+import { captureException } from '~/common/utils/posthog'
+import { UUIDT } from '~/common/utils/utils'
+
+import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginsServerConfig, Team } from '../../types'
+import type { CyclotronV2DequeuedJob, CyclotronV2JobInit, CyclotronV2Worker } from '../services/cyclotron-v2'
+import {
+ BatchResolverState,
+ MAX_RESOLVER_ATTEMPTS,
+ deserializeResolverState,
+ serializeResolverState,
+} from '../services/hogflows/batch-resolver.types'
+import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'
+import { invocationToV2JobInit } from '../services/job-queue/job-queue-postgres-v2'
+import { CyclotronJobInvocation } from '../types'
+import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals, logEntry } from '../utils'
+import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'
+import { counterBatchHogFlowTriggerFailed } from './metrics'
+
+const RETRY_BACKOFF_MS = 5_000
+
+const counterBatchHogFlowAudienceTruncated = new Counter({
+ name: 'cdp_batch_hog_flow_audience_truncated',
+ help: 'A batch hog flow run hit the per-team maxAudienceSize cap before finishing the audience',
+ labelNames: ['hog_flow_id'],
+})
+
+const counterBatchHogFlowResolverPagesProcessed = new Counter({
+ name: 'cdp_batch_hog_flow_resolver_pages_processed',
+ help: 'Total pages processed by the cyclotron-based batch resolver',
+ labelNames: ['outcome'], // success | fetch_failure | terminal_write_failure | invalid_state
+})
+
+/**
+ * State machine carried in `cyclotron_jobs.state` per resolver job:
+ * cursor=null, pendingTerminal=undefined → fetch first page
+ * cursor=X, pendingTerminal=undefined → fetch next page
+ * pendingTerminal='completed'|'failed' → PUT Django, ack on 200
+ *
+ * Resolver only acks after terminal Django write succeeds — Django down
+ * means the job parks via cyclotron retry, no progress is lost.
+ */
+export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServerConfig> {
+ protected name = 'CdpCyclotronWorkerBatchResolve'
+
+ constructor(
+ config: PluginsServerConfig,
+ deps: CdpConsumerBaseDeps,
+ private cyclotronWorker: CyclotronV2Worker,
+ private hogFlowBatchPersonQueryService: HogFlowBatchPersonQueryService,
+ private internalFetchService: InternalFetchService
+ ) {
+ super(config, deps)
+ }
+
+ public override async start(): Promise<void> {
+ await super.start()
+
+ await this.cyclotronWorker.connect(async (jobs) => {
+ for (const job of jobs) {
+ await this.processResolverJob(job)
+ }
+ })
+
+ logger.info('🔁', `${this.name} started`)
+ }
+
+ public override async stop(): Promise<void> {
+ logger.info('💤', `${this.name} stopping...`)
+ await this.cyclotronWorker.disconnect()
+ await super.stop()
+ logger.info('💤', `${this.name} stopped`)
+ }
+
+ public isHealthy(): HealthCheckResult {
+ return this.cyclotronWorker.isHealthy()
+ ? new HealthCheckResultOk()
+ : new HealthCheckResultError('Cyclotron worker is not healthy', { name: this.name })
+ }
+
+ private async processResolverJob(job: CyclotronV2DequeuedJob): Promise<void> {
+ let state: BatchResolverState
+ try {
+ state = deserializeResolverState(job.state)
+ } catch (err) {
+ // Schema drift, corrupted state, or a job from an incompatible
+ // older deploy. None should happen in steady state — alert on
+ // the counter so we notice fast.
+ counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'invalid_state' }).inc()
+ logger.error('🔴', `${this.name} - invalid resolver state, failing job`, {
+ jobId: job.id,
+ teamId: job.teamId,
+ functionId: job.functionId,
+ parentRunId: job.parentRunId,
+ error: serializeError(err),
+ })
+ captureException(err, {
+ tags: { resolver_error: 'invalid_state', jobId: job.id, parentRunId: job.parentRunId ?? '' },
+ })
+ await job.fail()
+ return
+ }
+
+ try {
+ if (state.pendingTerminal) {
+ try {
+ await this.processTerminalWrite(job, state)
+ } catch (err) {
+ counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'terminal_write_failure' }).inc()
+ logger.error('🔴', `${this.name} - unexpected error in processTerminalWrite`, {
+ batchJobId: state.batchJobId,
+ pendingTerminal: state.pendingTerminal,
+ error: serializeError(err),
+ })
+ captureException(err, {
+ tags: { resolver_error: 'terminal_write_unhandled', batchJobId: state.batchJobId },
+ })
+ // Don't ack — leave the job parked so cyclotron's stall recovery
+ // picks it up and another worker can retry.
+ await job.reschedule({ scheduledAt: new Date(Date.now() + RETRY_BACKOFF_MS) })
+ }
+ return
+ }
+
+ if (state.totalEnqueued >= state.maxAudienceSize) {
+ await this.transitionToTruncatedTerminal(job, state)
+ return
+ }
+
+ await this.processOnePage(job, state)
+ } finally {
+ // Flush monitoring every dequeue, not just on terminal-write. Non-terminal
+ // paths (truncation log queued in processOnePage, failure log in
+ // transitionToFailedTerminal) would otherwise wait for a later terminal
+ // dequeue — under multi-replica that's a different worker, and under a
+ // restart it's gone entirely.
+ await this.hogFunctionMonitoringService.flush().catch((err) => {
+ logger.warn('⚠️', `${this.name} - failed to flush monitoring after resolver dequeue`, {
+ error: serializeError(err),
+ })
+ })
+ }
+ }
+
+ /**
+ * Fetch one page of audience and atomically enqueue children + advance state.
+ * On fetch failure, retries via cyclotron reschedule with backoff — cursor
+ * is preserved in state so the page replays cleanly.
+ */
+ private async processOnePage(job: CyclotronV2DequeuedJob, state: BatchResolverState): Promise<void> {
+ const [team, hogFlow] = await Promise.all([
+ this.deps.teamManager.getTeam(state.teamId),
+ this.hogFlowManager.getHogFlow(state.hogFlowId),
+ ])
+
+ if (!team || !hogFlow) {
+ logger.error('🔴', `${this.name} - missing team or hogflow, failing resolver`, {
+ teamId: state.teamId,
+ hogFlowId: state.hogFlowId,
+ batchJobId: state.batchJobId,
+ })
+ counterBatchHogFlowTriggerFailed.labels({ hog_flow_id: state.hogFlowId, reason: 'missing_entity' }).inc()
+ await this.transitionToFailedTerminal(job, state, 'Workflow or team was deleted mid-run')
+ return
+ }
+
+ let page
+ try {
+ page = await instrumentFn('cdpBatchResolve.getBlastRadiusPersons', () =>
+ this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(
+ team,
+ state.filters,
+ state.groupTypeIndex,
+ state.cursor
+ )
+ )
+ } catch (err) {
+ counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'fetch_failure' }).inc()
+ const nextAttempts = state.attempts + 1
+ if (nextAttempts >= MAX_RESOLVER_ATTEMPTS) {
+ logger.error(
+ '🔴',
+ `${this.name} - page fetch failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts`,
+ {
+ batchJobId: state.batchJobId,
+ cursor: state.cursor,
+ pagesProcessed: state.pagesProcessed,
+ error: serializeError(err),
+ }
+ )
+ await this.transitionToFailedTerminal(
+ job,
+ state,
+ `Audience fetch failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts`
+ )
+ return
+ }
+ logger.warn('⚠️', `${this.name} - page fetch failed, will retry`, {
+ batchJobId: state.batchJobId,
+ cursor: state.cursor,
+ pagesProcessed: state.pagesProcessed,
+ attempts: nextAttempts,
+ error: serializeError(err),
+ })
+ const retryState: BatchResolverState = { ...state, attempts: nextAttempts }
+ await job.reschedule({
+ scheduledAt: new Date(Date.now() + RETRY_BACKOFF_MS),
+ state: serializeResolverState(retryState),
+ })
+ return
+ }
+
+ // Hard cap: truncate the crossing page so totalEnqueued never exceeds
+ // maxAudienceSize. Without this, a page can push us over the cap by
+ // up to one full page's worth of children before the next dequeue
+ // notices and stops.
+ const remainingBudget = Math.max(0, state.maxAudienceSize - state.totalEnqueued)
+ const eligibleUsers = page.users_affected.slice(0, remainingBudget)
+ const pageTruncated = eligibleUsers.length < page.users_affected.length
+
+ const defaultVariables = mergeDefaultVariables(hogFlow.variables, state.variables)
+ const children: CyclotronV2JobInit[] = eligibleUsers.map((personId) =>
+ invocationToV2JobInit(
+ buildHogFlowInvocation({
+ siteUrl: this.config.SITE_URL,
+ parentRunId: state.batchJobId,
+ team,
+ hogFlowId: hogFlow.id,
+ personId,
+ defaultVariables,
+ })
+ )
+ )
+
+ const newState: BatchResolverState = {
+ ...state,
+ cursor: page.cursor,
+ totalEnqueued: state.totalEnqueued + children.length,
+ pagesProcessed: state.pagesProcessed + 1,
+ attempts: 0, // reset on successful page commit
+ }
+ if (!page.has_more || pageTruncated) {
+ newState.pendingTerminal = 'completed'
+ }
+
+ await job.bulkCreateAndCheckIn({
+ newJobs: children,
+ selfDisposition: {
+ kind: 'reschedule',
+ scheduledAt: new Date(),
+ state: serializeResolverState(newState),
+ },
+ })
+
+ if (pageTruncated) {
+ this.emitTruncationLog(newState)
+ }
+
+ counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'success' }).inc()
+
+ logger.info(
+ '📝',
+ `${this.name} - processed page for batch ${state.batchJobId}: ${children.length} persons (${newState.totalEnqueued} total, ${newState.pagesProcessed} pages)`
+ )
+ }
+
+ private emitTruncationLog(state: BatchResolverState): void {
+ counterBatchHogFlowAudienceTruncated.labels({ hog_flow_id: state.hogFlowId }).inc()
+ const message = `Audience reached the max cap of ${state.maxAudienceSize}, ${state.totalEnqueued} persons enqueued; the remainder did not receive this workflow.`
+ logger.warn('⚠️', `${this.name} - audience truncated`, {
+ batchJobId: state.batchJobId,
+ totalEnqueued: state.totalEnqueued,
+ maxAudienceSize: state.maxAudienceSize,
+ })
+ this.hogFunctionMonitoringService.queueLogs(
+ [
+ {
+ team_id: state.teamId,
+ log_source: 'hog_flow',
+ log_source_id: state.batchJobId,
+ instance_id: state.batchJobId,
+ ...logEntry('warn', message),
+ },
+ ],
+ 'hog_flow'
+ )
+ }
+
+ private async transitionToTruncatedTerminal(job: CyclotronV2DequeuedJob, state: BatchResolverState): Promise<void> {
+ this.emitTruncationLog(state)
+ const newState: BatchResolverState = {
+ ...state,
+ pendingTerminal: 'completed',
+ attempts: 0, // give the terminal write a fresh retry budget
+ }
+ await job.reschedule({ scheduledAt: new Date(), state: serializeResolverState(newState) })
+ }
+
+ private async transitionToFailedTerminal(
+ job: CyclotronV2DequeuedJob,
+ state: BatchResolverState,
+ reasonMessage: string
+ ): Promise<void> {
+ this.hogFunctionMonitoringService.queueLogs(
+ [
+ {
+ team_id: state.teamId,
+ log_source: 'hog_flow',
+ log_source_id: state.batchJobId,
+ instance_id: state.batchJobId,
+ ...logEntry('error', `Batch resolver failed: ${reasonMessage}`),
+ },
+ ],
+ 'hog_flow'
+ )
+
+ const newState: BatchResolverState = {
+ ...state,
+ pendingTerminal: 'failed',
+ attempts: 0, // give the terminal write a fresh retry budget
+ }
+ await job.reschedule({ scheduledAt: new Date(), state: serializeResolverState(newState) })
+ }
+
+ private async processTerminalWrite(job: CyclotronV2DequeuedJob, state: BatchResolverState): Promise<void> {
+ if (!state.pendingTerminal) {
+ await job.fail()
+ return
+ }
+
+ try {
+ await this.putBatchJobStatus(state.teamId, state.batchJobId, state.pendingTerminal)
+ } catch (err) {
+ counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'terminal_write_failure' }).inc()
+ const nextAttempts = state.attempts + 1
+ if (nextAttempts >= MAX_RESOLVER_ATTEMPTS) {
+ logger.error(
+ '🔴',
+ `${this.name} - terminal status write failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts; failing job`,
+ {
+ batchJobId: state.batchJobId,
+ pendingTerminal: state.pendingTerminal,
+ error: serializeError(err),
+ }
+ )
+ await job.fail()
+ return
+ }
+ logger.warn('⚠️', `${this.name} - terminal status write failed, will retry`, {
+ batchJobId: state.batchJobId,
+ pendingTerminal: state.pendingTerminal,
+ attempts: nextAttempts,
+ error: serializeError(err),
+ })
+ const retryState: BatchResolverState = { ...state, attempts: nextAttempts }
+ await job.reschedule({
+ scheduledAt: new Date(Date.now() + RETRY_BACKOFF_MS),
+ state: serializeResolverState(retryState),
+ })
+ return
+ }
+
+ // Monitoring flush happens in processResolverJob's finally block so every
+ // dequeue clears its own queued logs/metrics, not just terminal writes.
+ await job.ack()
+ logger.info('✅', `${this.name} - batch ${state.batchJobId} → ${state.pendingTerminal}`, {
+ totalEnqueued: state.totalEnqueued,
+ pagesProcessed: state.pagesProcessed,
+ })
+ }
+
+ private async putBatchJobStatus(teamId: number, batchJobId: string, status: 'completed' | 'failed'): Promise<void> {
+ const urlPath = `/api/projects/${teamId}/internal/hog_flows/batch_jobs/${batchJobId}/status` as const
+
+ const { fetchResponse, fetchError } = await this.internalFetchService.fetch({
+ urlPath,
+ fetchParams: {
+ method: 'PUT',
+ body: JSON.stringify({ status }),
+ timeoutMs: 10_000,
+ },
+ })
+
+ if (fetchError) {
+ throw fetchError
+ }
+ if (!fetchResponse) {
+ throw new Error('Empty response from Django')
+ }
+ if (fetchResponse.status !== 200) {
+ const errorText = await fetchResponse.text()
+ throw new Error(`Django returned ${fetchResponse.status}: ${errorText}`)
+ }
+ }
+}
+
+function mergeDefaultVariables(
+ hogFlowVariables: Array<{ key: string; default?: unknown }> | undefined | null,
+ runOverrides: Record<string, unknown>
+): Record<string, unknown> {
+ const defaults: Record<string, unknown> = {}
+ for (const variable of hogFlowVariables ?? []) {
+ defaults[variable.key] = variable.default ?? null
+ }
+ return { ...defaults, ...runOverrides }
+}
+
+// Mirrors `createHogFlowInvocation` from the legacy Kafka consumer so children
+// land in cyclotron_jobs looking the same regardless of dispatch path.
+function buildHogFlowInvocation(params: {
+ siteUrl: string
+ parentRunId: string
+ team: Team
+ hogFlowId: string
+ personId: string
+ defaultVariables: Record<string, unknown>
+}): CyclotronJobInvocation {
+ const invocationGlobals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({
+ team: params.team,
+ personId: params.personId,
+ siteUrl: params.siteUrl,
+ })
+
+ const filterGlobals = convertToHogFunctionFilterGlobal(invocationGlobals)
+
+ return {
+ id: new UUIDT().toString(),
+ state: {
+ event: invocationGlobals.event,
+ personId: params.personId,
+ actionStepCount: 0,
+ variables: params.defaultVariables,
+ } as any,
+ teamId: params.team.id,
+ functionId: params.hogFlowId,
+ parentRunId: params.parentRunId,
+ person: invocationGlobals.person as any,
+ filterGlobals,
+ queue: 'hogflow' as const,
+ queuePriority: 1,
+ queueScheduledAt: DateTime.now(),
+ } as CyclotronJobInvocation
+}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index ffdf4b498a02..c9effbffa469 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -489,6 +489,172 @@ describe('Cyclotron V2', () => {
expect(jobs[0].queueName).toBe(QUEUE)
})
+ describe('bulkCreateAndCheckIn', () => {
+ it('atomically inserts new children and reschedules self', async () => {
+ const { id: parentId, job } = await seedAndDequeue()
+
+ const newState = Buffer.from(JSON.stringify({ cursor: 'next-page', totalEnqueued: 500 }))
+ const future = new Date(Date.now() + 60_000)
+
+ const result = await job.bulkCreateAndCheckIn({
+ newJobs: [
+ { teamId: 1, queueName: 'hogflow', parentRunId: parentId },
+ { teamId: 1, queueName: 'hogflow', parentRunId: parentId },
+ ],
+ selfDisposition: { kind: 'reschedule', scheduledAt: future, state: newState },
+ })
+
+ expect(result.newJobIds).toHaveLength(2)
+
+ // Self is back to available with new state + scheduled
+ const parent = await queryJob(parentId)
+ expect(parent.status).toBe('available')
+ expect(parent.lock_id).toBeNull()
+ expect(parent.state?.toString()).toBe(newState.toString())
+ expect(new Date(parent.scheduled).getTime()).toBeCloseTo(future.getTime(), -2)
+
+ // Children exist on their own queue
+ const children = await assertPool.query(
+ `SELECT id, queue_name, status, parent_run_id FROM cyclotron_jobs
+ WHERE parent_run_id = $1 ORDER BY id`,
+ [parentId]
+ )
+ expect(children.rows).toHaveLength(2)
+ expect(children.rows[0].queue_name).toBe('hogflow')
+ expect(children.rows[0].status).toBe('available')
+ })
+
+ it('acks self atomically with child inserts', async () => {
+ const { id: parentId, job } = await seedAndDequeue()
+
+ await job.bulkCreateAndCheckIn({
+ newJobs: [{ teamId: 1, queueName: 'hogflow', parentRunId: parentId }],
+ selfDisposition: { kind: 'ack' },
+ })
+
+ const parent = await queryJob(parentId)
+ expect(parent.status).toBe('completed')
+ expect(parent.lock_id).toBeNull()
+
+ expect(await countByStatus('available')).toBe(1) // child
+ })
+
+ it('fails self atomically with child inserts', async () => {
+ const { id: parentId, job } = await seedAndDequeue()
+
+ await job.bulkCreateAndCheckIn({
+ newJobs: [],
+ selfDisposition: { kind: 'fail' },
+ })
+
+ const parent = await queryJob(parentId)
+ expect(parent.status).toBe('failed')
+ })
+
+ it('handles empty newJobs (terminal page with no new children)', async () => {
+ const { id: parentId, job } = await seedAndDequeue()
+
+ const result = await job.bulkCreateAndCheckIn({
+ newJobs: [],
+ selfDisposition: { kind: 'ack' },
+ })
+
+ expect(result.newJobIds).toEqual([])
+ expect((await queryJob(parentId)).status).toBe('completed')
+ })
+
+ it('rolls back both writes if the insert fails (atomicity)', async () => {
+ const { id: parentId, job } = await seedAndDequeue()
+
+ // Force an insert failure by providing an invalid teamId
+ // (the schema parse will reject this before we even reach SQL,
+ // so the failure is pre-TX; verify self-state is untouched.)
+ await expect(
+ job.bulkCreateAndCheckIn({
+ newJobs: [{ teamId: 'bad-type' as any, queueName: 'hogflow' }],
+ selfDisposition: { kind: 'reschedule' },
+ })
+ ).rejects.toThrow()
+
+ // Parent still locked / running — no partial state
+ const parent = await queryJob(parentId)
+ expect(parent.status).toBe('running')
+ expect(parent.lock_id).not.toBeNull()
+ })
+
+ it('rolls back the self update when a child insert fails inside the TX', async () => {
+ // Real DB-level rollback path (vs the Zod pre-check above): two
+ // children with the same explicit id → second INSERT violates
+ // the PK constraint mid-TX → the self UPDATE must roll back too.
+ const { id: parentId, job } = await seedAndDequeue()
+ const duplicateId = '00000000-0000-0000-0000-000000000001'
+
+ await expect(
+ job.bulkCreateAndCheckIn({
+ newJobs: [
+ { id: duplicateId, teamId: 1, queueName: 'hogflow' },
+ { id: duplicateId, teamId: 1, queueName: 'hogflow' },
+ ],
+ selfDisposition: { kind: 'reschedule' },
+ })
+ ).rejects.toThrow()
+
+ // Self row untouched — still locked and running
+ const parent = await queryJob(parentId)
+ expect(parent.status).toBe('running')
+ expect(parent.lock_id).not.toBeNull()
+
+ // No children persisted
+ const children = await assertPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE parent_run_id IS NOT NULL OR id = $1`,
+ [duplicateId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('rolls back when the lock_id has been reassigned between dequeue and commit (janitor race)', async () => {
+ // Simulates the janitor's stall-recovery: the worker holds the
+ // dequeued job, but while it's mid-page the janitor decides the
+ // job stalled and reassigns the lock to another worker. The
+ // current TX's self UPDATE then matches zero rows because the
+ // WHERE lock_id = $2 filter fails. Without a rowCount guard,
+ // the child inserts would commit silently while the cursor
+ // doesn't advance — up to ~500 duplicate sends per page on
+ // replay by the other worker.
+ const { id: parentId, job } = await seedAndDequeue()
+
+ // Forcibly change the lock_id from underneath the worker.
+ await assertPool.query(`UPDATE cyclotron_jobs SET lock_id = gen_random_uuid() WHERE id = $1`, [
+ parentId,
+ ])
+
+ await expect(
+ job.bulkCreateAndCheckIn({
+ newJobs: [{ teamId: 1, queueName: 'hogflow', parentRunId: parentId }],
+ selfDisposition: { kind: 'reschedule' },
+ })
+ ).rejects.toThrow()
+
+ // No child rows leaked through
+ const children = await assertPool.query(`SELECT id FROM cyclotron_jobs WHERE parent_run_id = $1`, [
+ parentId,
+ ])
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('throws if the job was already released', async () => {
+ const { job } = await seedAndDequeue()
+ await job.ack()
+
+ await expect(
+ job.bulkCreateAndCheckIn({
+ newJobs: [],
+ selfDisposition: { kind: 'ack' },
+ })
+ ).rejects.toThrow('already released')
+ })
+ })
+
describe('CyclotronV2RateLimitedWorker', () => {
// The hook is consulted on every poll. It receives the number of
// rows actually visible (capped at batchMaxSize). Returning a
diff --git a/nodejs/src/cdp/services/cyclotron-v2/index.ts b/nodejs/src/cdp/services/cyclotron-v2/index.ts
index eccf0666cbd5..8f785d3a7230 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/index.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/index.ts
@@ -13,4 +13,6 @@ export type {
CyclotronV2JanitorConfig,
CyclotronV2CleanupResult,
CyclotronV2BatchLimit,
+ CyclotronV2BulkCreateAndCheckInInput,
+ CyclotronV2JobProducer,
} from './types'
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index c2a2642579e4..4d7cd9498de3 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -42,6 +42,29 @@ export const CyclotronV2RescheduleOptionsSchema = z.object({
export type CyclotronV2RescheduleOptions = z.infer<typeof CyclotronV2RescheduleOptionsSchema>
+/**
+ * Atomic enqueue-and-check-in primitive for fan-out workflows.
+ *
+ * Produces N new jobs AND re-queues (or terminates) the current worker's job
+ * in a single Postgres transaction. Used by the batch resolver: each page
+ * inserts ~500 child workflow invocations AND advances its own cursor state
+ * atomically — so a worker crash between the two writes can't leak partial
+ * progress (children enqueued but cursor not advanced).
+ *
+ * `selfDisposition`:
+ * - `{ kind: 'reschedule', scheduledAt?, state? }` → re-queue self (status
+ * back to 'available') for the next page.
+ * - `{ kind: 'ack' }` → terminal success (completed).
+ * - `{ kind: 'fail' }` → terminal failure.
+ */
+export interface CyclotronV2BulkCreateAndCheckInInput {
+ newJobs: CyclotronV2JobInit[]
+ selfDisposition:
+ | { kind: 'reschedule'; scheduledAt?: Date; state?: Buffer | null }
+ | { kind: 'ack' }
+ | { kind: 'fail' }
+}
+
export interface CyclotronV2DequeuedJob {
readonly id: string
readonly teamId: number
@@ -62,6 +85,7 @@ export interface CyclotronV2DequeuedJob {
reschedule(options?: CyclotronV2RescheduleOptions): Promise<void>
cancel(): Promise<void>
heartbeat(): Promise<void>
+ bulkCreateAndCheckIn(input: CyclotronV2BulkCreateAndCheckInInput): Promise<{ newJobIds: string[] }>
}
export type CyclotronV2ManagerConfig = {
@@ -70,6 +94,16 @@ export type CyclotronV2ManagerConfig = {
depthCheckIntervalMs?: number
}
+/**
+ * Producer-side surface of `CyclotronV2Manager`. Lets API entrypoints depend
+ * on the interface (testable, mockable) without pulling the full manager
+ * implementation. Add methods here as new producers need them.
+ */
+export interface CyclotronV2JobProducer {
+ createJob(input: CyclotronV2JobInit): Promise<string>
+ disconnect(): Promise<void>
+}
+
/**
* Per-poll decision returned by a rate-limited worker's hook.
* `{ limit: 0, sleepMs }` → skip the dequeue and sleep.
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index ef3795252692..2f42c75c06ee 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -1,12 +1,15 @@
import { DateTime } from 'luxon'
-import { Pool } from 'pg'
+import { Pool, PoolClient } from 'pg'
import { v7 as uuidv7 } from 'uuid'
import { logger } from '~/common/utils/logger'
import { assignEmailDequeueSeq } from './manager'
import {
+ CyclotronV2BulkCreateAndCheckInInput,
CyclotronV2DequeuedJob,
+ CyclotronV2JobInit,
+ CyclotronV2JobInitSchema,
CyclotronV2RescheduleOptions,
CyclotronV2RescheduleOptionsSchema,
CyclotronV2WorkerConfig,
@@ -33,6 +36,163 @@ export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
+/**
+ * Insert N new jobs within an open transaction. Mirrors the bulk-insert shape
+ * from `CyclotronV2Manager.bulkCreateJobs` but runs on a caller-provided
+ * client so the inserts can be wrapped in the same transaction as a sibling
+ * UPDATE (used by `bulkCreateAndCheckIn`).
+ *
+ * Intentionally narrower than manager.bulkCreateJobs: no `overwriteExisting`
+ * path, no email-queue `dequeue_seq` computation (the resolver enqueues
+ * children onto 'hogflow', not 'email'). Email re-routing happens later via
+ * the worker's reschedule path which already handles dequeue_seq assignment.
+ */
+async function insertNewJobsInTx(client: PoolClient, newJobs: CyclotronV2JobInit[]): Promise<string[]> {
+ if (newJobs.length === 0) {
+ return []
+ }
+
+ const now = new Date()
+ const ids: string[] = []
+ const teamIds: number[] = []
+ const functionIds: (string | null)[] = []
+ const queueNames: string[] = []
+ const priorities: number[] = []
+ const scheduleds: Date[] = []
+ const parentRunIds: (string | null)[] = []
+ const states: (Buffer | null)[] = []
+ const distinctIds: (string | null)[] = []
+ const personIds: (string | null)[] = []
+ const actionIds: (string | null)[] = []
+
+ for (const job of newJobs) {
+ ids.push(job.id ?? uuidv7())
+ teamIds.push(job.teamId)
+ functionIds.push(job.functionId ?? null)
+ queueNames.push(job.queueName)
+ priorities.push(job.priority ?? 0)
+ scheduleds.push(job.scheduled ?? now)
+ parentRunIds.push(job.parentRunId ?? null)
+ states.push(job.state ?? null)
+ distinctIds.push(job.distinctId ?? null)
+ personIds.push(job.personId ?? null)
+ actionIds.push(job.actionId ?? null)
+ }
+
+ await client.query(
+ `INSERT INTO cyclotron_jobs
+ (id, team_id, function_id, queue_name, status, priority, scheduled, created,
+ lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,
+ parent_run_id, state, distinct_id, person_id, action_id)
+ SELECT
+ unnest($1::uuid[]),
+ unnest($2::int[]),
+ unnest($3::uuid[]),
+ unnest($4::text[]),
+ 'available'::CyclotronJobStatus,
+ unnest($5::smallint[]),
+ unnest($6::timestamptz[]),
+ $12::timestamptz,
+ NULL::uuid,
+ NULL::timestamptz,
+ 0::smallint,
+ 0::smallint,
+ $12::timestamptz,
+ unnest($7::text[]),
+ unnest($8::bytea[]),
+ unnest($9::text[]),
+ unnest($10::text[]),
+ unnest($11::text[])`,
+ [
+ ids,
+ teamIds,
+ functionIds,
+ queueNames,
+ priorities,
+ scheduleds,
+ parentRunIds,
+ states,
+ distinctIds,
+ personIds,
+ actionIds,
+ now,
+ ]
+ )
+
+ return ids
+}
+
+/**
+ * Update the current worker's job row to reflect the chosen disposition
+ * (reschedule for next page / ack / fail). Mirrors the SQL shapes used by
+ * the wrapper's `ack`, `fail`, and `reschedule` methods, but runs in a
+ * caller-provided transaction so it can be atomic with sibling inserts.
+ *
+ * Throws if the UPDATE doesn't match exactly one row. The `WHERE lock_id`
+ * filter can match zero rows if the janitor reassigns the lock between
+ * dequeue and commit (stall-recovery race) — without this guard the child
+ * inserts would commit while the self UPDATE silently no-ops, leaving the
+ * cursor un-advanced for the new lock-holder to replay.
+ */
+async function updateSelfInTx(
+ client: PoolClient,
+ jobId: string,
+ lockId: string,
+ disposition: CyclotronV2BulkCreateAndCheckInInput['selfDisposition']
+): Promise<void> {
+ if (disposition.kind === 'ack') {
+ const result = await client.query(
+ `UPDATE cyclotron_jobs
+ SET status = 'completed', lock_id = NULL, last_heartbeat = NULL,
+ last_transition = NOW(), transition_count = transition_count + 1
+ WHERE id = $1 AND lock_id = $2`,
+ [jobId, lockId]
+ )
+ assertSelfRowAffected(result.rowCount, jobId, 'ack')
+ return
+ }
+ if (disposition.kind === 'fail') {
+ const result = await client.query(
+ `UPDATE cyclotron_jobs
+ SET status = 'failed', lock_id = NULL, last_heartbeat = NULL,
+ last_transition = NOW(), transition_count = transition_count + 1
+ WHERE id = $1 AND lock_id = $2`,
+ [jobId, lockId]
+ )
+ assertSelfRowAffected(result.rowCount, jobId, 'fail')
+ return
+ }
+ // reschedule
+ const scheduled = disposition.scheduledAt ?? new Date()
+ const setClauses = [
+ `status = 'available'`,
+ `lock_id = NULL`,
+ `last_heartbeat = NULL`,
+ `last_transition = NOW()`,
+ `transition_count = transition_count + 1`,
+ `scheduled = $3`,
+ ]
+ const params: any[] = [jobId, lockId, scheduled]
+ if (disposition.state !== undefined) {
+ params.push(disposition.state ?? null)
+ setClauses.push(`state = $${params.length}`)
+ }
+ const result = await client.query(
+ `UPDATE cyclotron_jobs SET ${setClauses.join(', ')}
+ WHERE id = $1 AND lock_id = $2`,
+ params
+ )
+ assertSelfRowAffected(result.rowCount, jobId, 'reschedule')
+}
+
+function assertSelfRowAffected(rowCount: number | null, jobId: string, kind: string): void {
+ if (rowCount !== 1) {
+ throw new Error(
+ `bulkCreateAndCheckIn(${kind}) self UPDATE matched ${rowCount} rows for job ${jobId} — lock_id may have been reassigned`
+ )
+ }
+}
+
export class CyclotronV2Worker {
private pool: Pool
protected isConsuming = false
@@ -358,6 +518,37 @@ export class CyclotronV2Worker {
[row.id, lockId]
)
},
+
+ async bulkCreateAndCheckIn(input: CyclotronV2BulkCreateAndCheckInInput): Promise<{ newJobIds: string[] }> {
+ releaseGuard('bulkCreateAndCheckIn')
+
+ // Validate new jobs up front, outside the TX, so a malformed
+ // input doesn't burn a connection slot mid-transaction.
+ const newJobs: CyclotronV2JobInit[] = input.newJobs.map((j) => CyclotronV2JobInitSchema.parse(j))
+
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+
+ const newJobIds = await insertNewJobsInTx(client, newJobs)
+ await updateSelfInTx(client, row.id, lockId, input.selfDisposition)
+
+ await client.query('COMMIT')
+ return { newJobIds }
+ } catch (err) {
+ try {
+ await client.query('ROLLBACK')
+ } catch (rollbackErr) {
+ logger.warn('bulkCreateAndCheckIn rollback failed', {
+ error: String(rollbackErr),
+ originalError: String(err),
+ })
+ }
+ throw err
+ } finally {
+ client.release()
+ }
+ },
}
}
diff --git a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts
new file mode 100644
index 000000000000..31f8d7bec40a
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts
@@ -0,0 +1,53 @@
+import { z } from 'zod'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+// Plain FIFO; resolver self-requeues per page so concurrent batches rotate naturally.
+export const HOGFLOW_BATCH_RESOLVE_QUEUE = 'hogflow_batch_resolve' as const
+
+// Caps how many times a single resolver job may retry a transient failure
+// (audience fetch or terminal status PUT). Once exhausted in the fetch path
+// the resolver flips to `pendingTerminal: 'failed'` so the Django row reaches
+// a terminal state; in the terminal-write path the cyclotron job itself
+// fails so the janitor can clean it up.
+export const MAX_RESOLVER_ATTEMPTS = 5
+
+// Zod-validated on every dequeue so a job written by an older deploy fails
+// cleanly at the boundary instead of crashing later in the page logic.
+export const BatchResolverStateSchema = z.object({
+ batchJobId: z.string().min(1),
+ teamId: z.number().int(),
+ hogFlowId: z.string().min(1),
+ filters: z.object({
+ // Each property entry is an arbitrary record — keep loose so resolver
+ // replays survive new filter-property fields the worker doesn't read.
+ properties: z.array(z.record(z.string(), z.any())).optional(),
+ filter_test_accounts: z.boolean().optional(),
+ }),
+ variables: z.record(z.string(), z.unknown()),
+ groupTypeIndex: z.number().int().optional(),
+ maxAudienceSize: z.number().int().nonnegative(),
+ cursor: z.string().nullable(),
+ totalEnqueued: z.number().int().nonnegative(),
+ pagesProcessed: z.number().int().nonnegative(),
+ // Resets to 0 on each successful page transition. Increments on every
+ // retry path (fetch failure, terminal write failure). Old job rows
+ // without this field default to 0 via the zod parse.
+ attempts: z.number().int().nonnegative().default(0),
+ startedAt: z.string(),
+ pendingTerminal: z.enum(['completed', 'failed']).optional(),
+})
+
+export type BatchResolverState = z.infer<typeof BatchResolverStateSchema>
+
+export function serializeResolverState(state: BatchResolverState): Buffer {
+ return Buffer.from(JSON.stringify(state))
+}
+
+export function deserializeResolverState(buf: Buffer | null): BatchResolverState {
+ if (!buf) {
+ throw new Error('Resolver job is missing state')
+ }
+ const parsed: unknown = parseJSON(buf.toString('utf-8'))
+ return BatchResolverStateSchema.parse(parsed)
+}
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.ts
index f1216b1d8605..e774abac79e1 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
@@ -272,7 +272,7 @@ function serializeState(invocation: CyclotronJobInvocation): Buffer {
return Buffer.from(JSON.stringify(blob))
}
-function invocationToV2JobInit(invocation: CyclotronJobInvocation): CyclotronV2JobInit {
+export function invocationToV2JobInit(invocation: CyclotronJobInvocation): CyclotronV2JobInit {
const state = serializeState(invocation)
cdpJobSizeKb.labels('postgres-v2').observe(state.length / 1024)
cdpJobSizeCompressedKb.labels('postgres-v2').observe(state.length / 1024)
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 43ede5c78377..8dad82122a10 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -11,21 +11,26 @@
* state serialization.
*/
import { MockKafkaProducerWrapper } from '~/tests/helpers/mocks/producer.mock'
-import { mockFetch } from '~/tests/helpers/mocks/request.mock'
+import { mockFetch, mockInternalFetch } from '~/tests/helpers/mocks/request.mock'
import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'
import { DateTime } from 'luxon'
import { Pool } from 'pg'
import { register } from 'prom-client'
+import supertest from 'supertest'
+import express from 'ultimate-express'
import { HogFlow } from '~/cdp/schema/hogflow'
+import { setupExpressApp } from '~/common/api/router'
import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { InternalPersonWithDistinctId, PersonReadRepository } from '~/common/persons/repositories/person-repository'
import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
+import { InternalFetchService } from '~/common/services/internal-fetch'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
+import { parseJSON } from '~/common/utils/json-parse'
import { UUIDT } from '~/common/utils/utils'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { waitForExpect } from '~/tests/helpers/expectations'
@@ -38,11 +43,20 @@ import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES } from './_tests/examples'
import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from './_tests/fixtures'
import { insertHogFlow } from './_tests/fixtures-hogflows'
+import { CdpApi } from './cdp-api'
+import { CdpCyclotronWorkerBatchResolve } from './consumers/cdp-cyclotron-worker-batch-resolve.consumer'
import { CdpCyclotronWorkerEmail } from './consumers/cdp-cyclotron-worker-email.consumer'
import { CdpCyclotronWorkerHogFlow } from './consumers/cdp-cyclotron-worker-hogflow.consumer'
import { CdpDatawarehouseEventsConsumer } from './consumers/cdp-data-warehouse-events.consumer'
import { CdpEventsConsumer } from './consumers/cdp-events.consumer'
import { CdpHogflowSubscriptionMatcherConsumer } from './consumers/cdp-hogflow-subscription-matcher.consumer'
+import { CyclotronV2Manager, CyclotronV2Worker } from './services/cyclotron-v2'
+import {
+ HOGFLOW_BATCH_RESOLVE_QUEUE,
+ MAX_RESOLVER_ATTEMPTS,
+ serializeResolverState,
+} from './services/hogflows/batch-resolver.types'
+import { HogFlowBatchPersonQueryService } from './services/hogflows/hogflow-batch-person-query.service'
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'
@@ -2602,3 +2616,770 @@ describe('Workflows E2E (email queue)', () => {
expect(pool).toBeGreaterThanOrEqual(capacity - 1)
})
})
+
+/**
+ * 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.
+ *
+ * The deep state-machine paths (page execution, terminal write, truncation,
+ * Django down → resolver parks) are covered by the integration tests in
+ * `consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts`. This
+ * test is the boundary backstop — it caught a real bug (wrong DB URL on
+ * the resolver manager) during development.
+ *
+ * Hub lifecycle follows cdp-api.test.ts: one hub for the suite (beforeAll),
+ * torn down once (afterAll). Per-test isolation comes from resetting the
+ * postgres team data + truncating cyclotron_jobs in beforeEach.
+ */
+
+/**
+ * E2E for the cyclotron batch resolver. POST through cdp-api, real consumer
+ * loop, mocked Django endpoints, assert on the resulting cyclotron + Django
+ * state. Mirrors how the system runs in prod — no manual dequeue plumbing.
+ */
+describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {
+ jest.setTimeout(60000)
+
+ const CYCLOTRON_NODE_DB_URL =
+ process.env.CYCLOTRON_NODE_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'
+
+ let hub: Hub
+ let team: Team
+ let cyclotronPool: Pool
+ let app: express.Application
+ let server: any
+ let api: CdpApi
+ let batchResolverProducer: CyclotronV2Manager
+ let deps: ReturnType<typeof createCdpConsumerDeps>
+ // Fresh consumer per test — built in the it() body, stopped in afterEach.
+ let resolverWorker: CdpCyclotronWorkerBatchResolve | undefined
+
+ beforeAll(async () => {
+ cyclotronPool = new Pool({ connectionString: CYCLOTRON_NODE_DB_URL })
+
+ MockKafkaProducerWrapper.create = jest.fn((...args) => ActualKafkaProducerWrapper.create(...args))
+ await ensureKafkaTopics(TEST_KAFKA_TOPICS)
+
+ hub = await createHub({
+ SITE_URL: 'http://localhost:8000',
+ CDP_BATCH_RESOLVER_ROUTING: '*',
+ })
+
+ const { createMockJobQueue } = require('../../tests/helpers/mocks/job-queue.mock')
+ deps = createCdpConsumerDeps(hub)
+ batchResolverProducer = new CyclotronV2Manager({
+ pool: { dbUrl: CYCLOTRON_NODE_DB_URL, maxConnections: 5 },
+ })
+ api = new CdpApi(
+ hub,
+ deps,
+ { hogQueue: createMockJobQueue(), hogflowQueue: createMockJobQueue() },
+ batchResolverProducer
+ )
+ app = setupExpressApp()
+ app.use('/', api.router())
+ server = app.listen(0, () => {})
+ })
+
+ afterAll(async () => {
+ server?.close()
+ await batchResolverProducer?.disconnect()
+ await closeHub(hub)
+ await cyclotronPool.end()
+ })
+
+ beforeEach(async () => {
+ await resetTestDatabase()
+ await cyclotronPool.query(`DELETE FROM cyclotron_jobs`)
+ team = await getFirstTeam(hub.postgres)
+ api['batchResolverRoutingMatcher'] = () => true
+ resolverWorker = undefined
+ })
+
+ afterEach(async () => {
+ // If the test started the consumer, shut it down before the next test.
+ // resolverWorker.stop() waits for any in-flight processBatch to settle,
+ // then closes the pool — so afterAll's closeHub has no leftover work.
+ await resolverWorker?.stop()
+ })
+
+ // Fresh worker per test — stop() disconnects the underlying Postgres pool,
+ // so a shared instance can't survive past the first test's afterEach.
+ function buildResolverConsumer(): CdpCyclotronWorkerBatchResolve {
+ const cyclotronWorker = new CyclotronV2Worker({
+ pool: { dbUrl: CYCLOTRON_NODE_DB_URL, maxConnections: 10 },
+ queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
+ pollDelayMs: 100,
+ })
+ const internalFetchService = new InternalFetchService(hub.INTERNAL_API_BASE_URL, hub.INTERNAL_API_SECRET)
+ const queryService = new HogFlowBatchPersonQueryService(internalFetchService)
+ return new CdpCyclotronWorkerBatchResolve(hub, deps, cyclotronWorker, queryService, internalFetchService)
+ }
+
+ async function insertActiveBatchFlow(): Promise<HogFlow> {
+ const flow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: {
+ type: 'batch',
+ filters: { properties: [{ key: 'plan', value: 'enterprise', type: 'person' }] },
+ },
+ },
+ function_1: {
+ type: 'function',
+ config: {
+ template_id: 'template-workflows-e2e-fetch',
+ inputs: { url: { value: 'https://example.com/batch' } },
+ },
+ },
+ },
+ edges: [{ from: 'trigger', to: 'function_1', type: 'continue' }],
+ })
+ .build()
+ return await insertHogFlow(hub.postgres, flow)
+ }
+
+ it('POST /batch_invocations with flag on creates a resolver cyclotron job with the right shape', async () => {
+ 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 },
+ max_audience_size: 750,
+ variables: { greeting: 'hi' },
+ group_type_index: 2,
+ })
+ .expect(200)
+
+ expect(response.body).toEqual({ status: 'queued' })
+
+ const rows = await cyclotronPool.query<{
+ id: string
+ queue_name: string
+ status: string
+ parent_run_id: string
+ team_id: number
+ function_id: string
+ state: Buffer | null
+ }>(
+ `SELECT id, queue_name, status::text AS status, parent_run_id, team_id, function_id, state
+ FROM cyclotron_jobs
+ WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(rows.rows).toHaveLength(1)
+ const job = rows.rows[0]
+ expect(job.status).toBe('available')
+ expect(job.parent_run_id).toBe(parentRunId)
+ expect(job.team_id).toBe(team.id)
+ expect(job.function_id).toBe(flow.id)
+
+ const state = parseJSON((job.state as Buffer).toString('utf-8')) as Record<string, unknown>
+ expect(state).toMatchObject({
+ batchJobId: parentRunId,
+ teamId: team.id,
+ hogFlowId: flow.id,
+ maxAudienceSize: 750,
+ variables: { greeting: 'hi' },
+ groupTypeIndex: 2,
+ cursor: null,
+ totalEnqueued: 0,
+ pagesProcessed: 0,
+ })
+ 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)
+ .withStatus('active')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: {} },
+ },
+ function_1: {
+ type: 'function',
+ config: {
+ template_id: 'template-workflows-e2e-fetch',
+ inputs: { url: { value: 'https://example.com/' } },
+ },
+ },
+ },
+ edges: [{ from: 'trigger', to: 'function_1', type: 'continue' }],
+ })
+ .build()
+ const inserted = await insertHogFlow(hub.postgres, flow)
+ const parentRunId = new UUIDT().toString()
+
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${inserted.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false } })
+ .expect(400)
+
+ const rows = await cyclotronPool.query(`SELECT id FROM cyclotron_jobs WHERE parent_run_id = $1`, [parentRunId])
+ expect(rows.rows).toHaveLength(0)
+ })
+
+ it('full lifecycle: HTTP POST → resolver chunks 3 pages → children enqueued → Django PUT status=completed', async () => {
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+
+ const personIds = [
+ new UUIDT().toString(),
+ new UUIDT().toString(),
+ new UUIDT().toString(),
+ new UUIDT().toString(),
+ new UUIDT().toString(),
+ ]
+ const statusPuts: Array<{ status: string }> = []
+ let personPageCalls = 0
+
+ mockInternalFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ personPageCalls += 1
+ const pages = [
+ { users_affected: personIds.slice(0, 2), cursor: 'c1', has_more: true },
+ { users_affected: personIds.slice(2, 4), cursor: 'c2', has_more: true },
+ { users_affected: personIds.slice(4), cursor: null, has_more: false },
+ ]
+ const page = pages[Math.min(personPageCalls - 1, pages.length - 1)]
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(JSON.stringify(page)),
+ dump: () => Promise.resolve(),
+ })
+ }
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })
+ .expect(200)
+
+ // Start the consumer — it'll pick up the resolver job and process pages
+ // on its own polling loop. waitForExpect waits for the terminal Django
+ // PUT, which only happens after all 3 pages + the terminal-write phase.
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(statusPuts).toHaveLength(1)
+ }, 20000)
+
+ expect(personPageCalls).toBe(3)
+ expect(statusPuts[0]).toEqual({ status: 'completed' })
+
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(personIds.length)
+ })
+
+ it('failed lifecycle: workflow deleted before processing → resolver transitions to failed → Django PUT status=failed', async () => {
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const statusPuts: Array<{ status: string }> = []
+
+ mockInternalFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ // Audience fetch shouldn't be reached — the resolver bails on missing
+ // hogflow before getting that far.
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ // Dispatch BEFORE starting the consumer so we can sabotage the workflow
+ // before any processing happens (otherwise the consumer would race us
+ // and process the job before we delete the workflow).
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })
+ .expect(200)
+
+ // Sabotage: customer deletes the workflow between dispatch and processing.
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `DELETE FROM posthog_hogflow WHERE id = $1`,
+ [flow.id],
+ 'delete-hogflow-for-test'
+ )
+ // The consumer we're about to build will have its own hogFlowManager
+ // with an empty cache, so refresh isn't strictly needed — but be
+ // explicit so the test isn't sensitive to cache lifecycle changes.
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(statusPuts).toHaveLength(1)
+ }, 20000)
+
+ expect(statusPuts[0]).toEqual({ status: 'failed' })
+
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('Django down: resolver retries the terminal PUT instead of acking', async () => {
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const personIds = [new UUIDT().toString()]
+ let putAttempts = 0
+
+ mockInternalFetch.mockImplementation((url: string) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () =>
+ Promise.resolve(
+ JSON.stringify({
+ users_affected: personIds,
+ cursor: null,
+ has_more: false,
+ })
+ ),
+ dump: () => Promise.resolve(),
+ })
+ }
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ putAttempts += 1
+ return Promise.resolve({
+ status: 503,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('Service Unavailable'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })
+ .expect(200)
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ // Wait until at least one Django PUT attempt has happened — proves the
+ // resolver reached the terminal-write phase. Then verify the resolver
+ // job is parked (status='available' with pendingTerminal still set),
+ // not acked.
+ await waitForExpect(() => {
+ expect(putAttempts).toBeGreaterThanOrEqual(1)
+ }, 20000)
+
+ const rows = await cyclotronPool.query<{ status: string; state: Buffer | null }>(
+ `SELECT status::text AS status, state FROM cyclotron_jobs
+ WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(rows.rows).toHaveLength(1)
+ expect(rows.rows[0].status).toBe('available')
+ const state = parseJSON((rows.rows[0].state as Buffer).toString('utf-8')) as { pendingTerminal?: string }
+ expect(state.pendingTerminal).toBe('completed')
+ })
+
+ it('audience fetch failure: resolver reschedules with backoff, cursor unchanged, no children enqueued', async () => {
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ let fetchAttempts = 0
+
+ mockInternalFetch.mockImplementation((url: string) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ fetchAttempts += 1
+ // Audience fetch always fails — resolver should keep retrying,
+ // never advance the cursor, never enqueue children.
+ return Promise.reject(new Error('The operation was aborted due to timeout'))
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })
+ .expect(200)
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(fetchAttempts).toBeGreaterThanOrEqual(1)
+ }, 20000)
+
+ const rows = await cyclotronPool.query<{ status: string; state: Buffer | null }>(
+ `SELECT status::text AS status, state FROM cyclotron_jobs
+ WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(rows.rows).toHaveLength(1)
+ expect(rows.rows[0].status).toBe('available')
+ const state = parseJSON((rows.rows[0].state as Buffer).toString('utf-8')) as {
+ cursor: string | null
+ totalEnqueued: number
+ pagesProcessed: number
+ pendingTerminal?: string
+ }
+ expect(state.cursor).toBeNull() // never advanced
+ expect(state.totalEnqueued).toBe(0)
+ expect(state.pagesProcessed).toBe(0)
+ expect(state.pendingTerminal).toBeUndefined()
+
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('truncation: pre-existing job at maxAudienceSize skips fetch + emits customer log + writes status=completed', async () => {
+ // Pre-populate a resolver job at the cap so the next dequeue takes
+ // the truncation branch (audience fetch never runs).
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const statusPuts: Array<{ status: string }> = []
+
+ mockInternalFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ const cappedState = serializeResolverState({
+ batchJobId: parentRunId,
+ teamId: team.id,
+ hogFlowId: flow.id,
+ filters: { properties: [], filter_test_accounts: false },
+ variables: {},
+ maxAudienceSize: 100,
+ cursor: 'some-cursor',
+ totalEnqueued: 100,
+ pagesProcessed: 1,
+ attempts: 0,
+ startedAt: new Date().toISOString(),
+ })
+ await batchResolverProducer.createJob({
+ teamId: team.id,
+ queueName: 'hogflow_batch_resolve',
+ parentRunId,
+ functionId: flow.id,
+ state: cappedState,
+ })
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(statusPuts).toHaveLength(1)
+ }, 20000)
+
+ // Status PUT was completed (truncation is still success, not failure)
+ expect(statusPuts[0]).toEqual({ status: 'completed' })
+
+ // No children — the resolver short-circuited before audience fetch
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('persistent fetch failure exhausts MAX_RESOLVER_ATTEMPTS → flips to pendingTerminal=failed and writes status=failed', async () => {
+ // Pre-populate a resolver job already one retry below the cap so we
+ // only need to drive a single more fetch failure to cross the
+ // threshold — avoids burning 5x backoff windows in CI.
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const statusPuts: Array<{ status: string }> = []
+ let fetchAttempts = 0
+
+ mockInternalFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ fetchAttempts += 1
+ return Promise.reject(new Error('ClickHouse permanently rejecting the audience query'))
+ }
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ const seededState = serializeResolverState({
+ batchJobId: parentRunId,
+ teamId: team.id,
+ hogFlowId: flow.id,
+ filters: { properties: [], filter_test_accounts: false },
+ variables: {},
+ maxAudienceSize: 1000,
+ cursor: null,
+ totalEnqueued: 0,
+ pagesProcessed: 0,
+ attempts: MAX_RESOLVER_ATTEMPTS - 1,
+ startedAt: new Date().toISOString(),
+ })
+ await batchResolverProducer.createJob({
+ teamId: team.id,
+ queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
+ parentRunId,
+ functionId: flow.id,
+ state: seededState,
+ })
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(statusPuts).toHaveLength(1)
+ }, 20000)
+
+ expect(statusPuts[0]).toEqual({ status: 'failed' })
+ expect(fetchAttempts).toBe(1) // one more retry consumed the last attempt budget
+
+ // No children enqueued — the resolver bailed before ever returning a page
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+
+ it('persistent Django 4xx on terminal write exhausts MAX_RESOLVER_ATTEMPTS → job.fail()', async () => {
+ // Pre-populate a job already in the terminal-write phase with attempts
+ // one below the cap. The 404 response is a permanent failure — no
+ // amount of retrying will make Django accept it (the row is gone) —
+ // so the resolver should give up and fail the cyclotron job instead
+ // of looping forever.
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ let putAttempts = 0
+
+ mockInternalFetch.mockImplementation((url: string) => {
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ putAttempts += 1
+ return Promise.resolve({
+ status: 404,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('Not Found'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ const pendingState = serializeResolverState({
+ batchJobId: parentRunId,
+ teamId: team.id,
+ hogFlowId: flow.id,
+ filters: { properties: [], filter_test_accounts: false },
+ variables: {},
+ maxAudienceSize: 1000,
+ cursor: 'last-cursor',
+ totalEnqueued: 5,
+ pagesProcessed: 1,
+ attempts: MAX_RESOLVER_ATTEMPTS - 1,
+ startedAt: new Date().toISOString(),
+ pendingTerminal: 'completed',
+ })
+ await batchResolverProducer.createJob({
+ teamId: team.id,
+ queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
+ parentRunId,
+ functionId: flow.id,
+ state: pendingState,
+ })
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(async () => {
+ const r = await cyclotronPool.query<{ status: string }>(
+ `SELECT status::text AS status FROM cyclotron_jobs
+ WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(r.rows[0]?.status).toBe('failed')
+ }, 20000)
+
+ // One more attempt consumed the budget, then the job failed
+ expect(putAttempts).toBe(1)
+ })
+
+ it('hard cap: page that would cross maxAudienceSize is truncated before enqueue', async () => {
+ // maxAudienceSize=4 with pages of 3. Without the hard cap the resolver
+ // would enqueue 6 children (overshoot by 2) then notice and truncate.
+ // With the hard cap the second page is truncated to 1 row so the
+ // total never exceeds 4.
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const personIds = Array.from({ length: 6 }, () => new UUIDT().toString())
+ const statusPuts: Array<{ status: string }> = []
+ let personPageCalls = 0
+
+ mockInternalFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ personPageCalls += 1
+ const pages = [
+ { users_affected: personIds.slice(0, 3), cursor: 'c1', has_more: true },
+ { users_affected: personIds.slice(3, 6), cursor: 'c2', has_more: true },
+ ]
+ const page = pages[Math.min(personPageCalls - 1, pages.length - 1)]
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(JSON.stringify(page)),
+ dump: () => Promise.resolve(),
+ })
+ }
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return Promise.resolve({
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ })
+ }
+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ })
+
+ await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)
+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 4 })
+ .expect(200)
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(() => {
+ expect(statusPuts).toHaveLength(1)
+ }, 20000)
+
+ expect(statusPuts[0]).toEqual({ status: 'completed' })
+
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ // Hard cap: exactly 4 children, never 6
+ expect(children.rows).toHaveLength(4)
+ })
+
+ it('invalid resolver state: garbage bytes → job.fail() (not retry)', async () => {
+ // Insert a resolver job with state that doesn't match the Zod schema.
+ // Simulates schema drift, corruption, or a row written by an
+ // incompatible older deploy. The resolver must FAIL the job (terminal)
+ // rather than reschedule — otherwise we'd retry-loop forever on a job
+ // that can never succeed.
+ const parentRunId = new UUIDT().toString()
+ const malformedState = Buffer.from(JSON.stringify({ not: 'a valid resolver state' }))
+ await batchResolverProducer.createJob({
+ teamId: team.id,
+ queueName: 'hogflow_batch_resolve',
+ parentRunId,
+ functionId: new UUIDT().toString(),
+ state: malformedState,
+ })
+
+ mockInternalFetch.mockImplementation((url: string) =>
+ Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))
+ )
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+
+ await waitForExpect(async () => {
+ const r = await cyclotronPool.query<{ status: string }>(
+ `SELECT status::text AS status FROM cyclotron_jobs
+ WHERE queue_name = 'hogflow_batch_resolve' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(r.rows[0]?.status).toBe('failed')
+ }, 20000)
+
+ // No children, no Django PUT — the resolver failed before any work.
+ const children = await cyclotronPool.query(
+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,
+ [parentRunId]
+ )
+ expect(children.rows).toHaveLength(0)
+ })
+})
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index c5e4f1b9cd3c..764fccd36169 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -41,6 +41,7 @@ export enum PluginServerMode {
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',
recording_api = 'recording-api',
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 448f2d58b6d1..e50062831fb1 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -9,6 +9,7 @@ import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group
import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
import { InternalCaptureService } from '~/common/services/internal-capture'
+import { InternalFetchService } from '~/common/services/internal-fetch'
import { QuotaLimiting } from '~/common/services/quota-limiting.service'
import { ServerCommands } from '~/common/utils/commands'
import { PostgresRouter } from '~/common/utils/db/postgres'
@@ -24,6 +25,7 @@ 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'
import { CdpCyclotronWorkerHogFlow } from './cdp/consumers/cdp-cyclotron-worker-hogflow.consumer'
import { CdpCyclotronWorker } from './cdp/consumers/cdp-cyclotron-worker.consumer'
@@ -37,8 +39,10 @@ import { CdpPrecalculatedFiltersConsumer } from './cdp/consumers/cdp-precalculat
import { CdpRerunWorkerConsumer } from './cdp/consumers/cdp-rerun-worker.consumer'
import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'
import { CdpProducerName } from './cdp/outputs/producers'
-import { CyclotronV2JanitorService } from './cdp/services/cyclotron-v2'
+import { CyclotronV2JanitorService, CyclotronV2Manager, CyclotronV2Worker } from './cdp/services/cyclotron-v2'
import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-schedule.service'
+import { HOGFLOW_BATCH_RESOLVE_QUEUE } from './cdp/services/hogflows/batch-resolver.types'
+import { HogFlowBatchPersonQueryService } from './cdp/services/hogflows/hogflow-batch-person-query.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'
@@ -100,6 +104,7 @@ export class PluginServer implements NodeServer {
capabilities.cdpPrecalculatedFilters ||
capabilities.cdpCohortMembership ||
capabilities.cdpBatchHogFlow ||
+ capabilities.cdpCyclotronWorkerBatchResolve ||
capabilities.cdpHogflowSubscriptionMatcher ||
capabilities.cdpRerunWorker
)
@@ -203,10 +208,20 @@ export class PluginServer implements NodeServer {
if (capabilities.cdpApi) {
serviceLoaders.push(async () => {
- const api = new CdpApi(this.config, cdpDeps!, {
- hogQueue: kafkaQueue,
- hogflowQueue: postgresV2Queue,
- })
+ // 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).
+ const batchResolverProducer = this.config.CYCLOTRON_NODE_DATABASE_URL
+ ? new CyclotronV2Manager({
+ pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL, maxConnections: 5 },
+ })
+ : null
+ const api = new CdpApi(
+ this.config,
+ cdpDeps!,
+ { hogQueue: kafkaQueue, hogflowQueue: postgresV2Queue },
+ batchResolverProducer
+ )
this.lifecycle.expressApp.use('/', api.router())
await api.start()
return api.service
@@ -372,6 +387,36 @@ export class PluginServer implements NodeServer {
})
}
+ if (capabilities.cdpCyclotronWorkerBatchResolve) {
+ serviceLoaders.push(async () => {
+ if (!this.config.CYCLOTRON_NODE_DATABASE_URL) {
+ throw new Error('CYCLOTRON_NODE_DATABASE_URL is required for CdpCyclotronWorkerBatchResolve')
+ }
+ const cyclotronWorker = new CyclotronV2Worker({
+ pool: {
+ dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL,
+ maxConnections: 10,
+ },
+ queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
+ pollDelayMs: 100,
+ })
+ const internalFetchService = new InternalFetchService(
+ this.config.INTERNAL_API_BASE_URL,
+ this.config.INTERNAL_API_SECRET
+ )
+ const hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(internalFetchService)
+ const consumer = new CdpCyclotronWorkerBatchResolve(
+ this.config,
+ cdpDeps!,
+ cyclotronWorker,
+ hogFlowBatchPersonQueryService,
+ internalFetchService
+ )
+ await consumer.start()
+ return consumer.service
+ })
+ }
+
const readyServices = await Promise.all(serviceLoaders.map((loader) => loader()))
this.lifecycle.services.push(...readyServices)
}
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index 0fbb0171fe02..44690d47d441 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -143,6 +143,7 @@ export interface PluginServerCapabilities {
cdpInternalEvents?: boolean
cdpLegacyOnEvent?: boolean
cdpBatchHogFlow?: boolean
+ cdpCyclotronWorkerBatchResolve?: boolean
cdpCyclotronWorker?: boolean
cdpCyclotronWorkerHogFlow?: boolean
cdpCyclotronWorkerHogFlowLegacyPg?: boolean
diff --git a/posthog/urls.py b/posthog/urls.py
index 732a7104b2ae..0092e25b366e 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -387,6 +387,10 @@ urlpatterns = [
"api/internal/hog_flows/process_due_schedules",
csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"post": "internal_process_due_schedules"})),
),
+ path(
+ "api/projects/<str:team_id>/internal/hog_flows/batch_jobs/<str:batch_job_id>/status",
+ csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"put": "internal_update_batch_job_status"})),
+ ),
path(
"api/projects/<str:team_id>/internal/signals/emit",
csrf_exempt(signals_views.InternalSignalViewSet.as_view({"post": "emit"})),
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 680824115f1d..93ad2425f4e2 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -4,6 +4,7 @@ import uuid as uuid_mod
from datetime import timedelta
from typing import Optional, cast
+from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import QuerySet
from django.utils import timezone
@@ -1847,3 +1848,72 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi
except Exception as e:
logger.exception("Error in internal_process_due_schedules", error=str(e))
return Response({"error": "Internal server error"}, status=500)
+
+ def internal_update_batch_job_status(self, request: Request, team_id: str, batch_job_id: str) -> Response:
+ """
+ Internal endpoint for the Node-side batch resolver to write the terminal
+ status of a HogFlowBatchJob run. Idempotent: if the row is already in a
+ terminal status, returns 200 without re-writing — the resolver retries
+ this call via cyclotron retry semantics, so safe repeats are required.
+
+ Accepts: { status: "completed" | "failed" }
+ """
+ from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob # noqa: PLC0415
+
+ if request.method != "PUT":
+ return Response({"error": "Method not allowed"}, status=405)
+
+ try:
+ team = Team.objects.get(id=int(team_id))
+ except (Team.DoesNotExist, ValueError):
+ return Response({"error": "Team not found"}, status=404)
+
+ new_status = request.data.get("status")
+ if new_status not in (HogFlowBatchJob.State.COMPLETED, HogFlowBatchJob.State.FAILED):
+ return Response(
+ {"error": "status must be one of: completed, failed"},
+ status=400,
+ )
+
+ try:
+ batch_job = HogFlowBatchJob.objects.get(id=batch_job_id, team=team)
+ except (HogFlowBatchJob.DoesNotExist, DjangoValidationError, ValueError):
+ # `DjangoValidationError` fires when `batch_job_id` is not a parseable
+ # UUID (UUIDField rejects it before the lookup). `ValueError` is a
+ # belt-and-suspenders catch for str→int / str→UUID edge cases on
+ # other backends. Either way, surface as 404, not 500.
+ return Response({"error": "Batch job not found"}, status=404)
+
+ terminal_states = {
+ HogFlowBatchJob.State.COMPLETED,
+ HogFlowBatchJob.State.FAILED,
+ HogFlowBatchJob.State.CANCELLED,
+ }
+ if batch_job.status in terminal_states:
+ # Idempotent no-op: already in a terminal state.
+ return Response(
+ {
+ "id": str(batch_job.id),
+ "status": batch_job.status,
+ "no_op": True,
+ }
+ )
+
+ try:
+ batch_job.status = new_status
+ batch_job.save(update_fields=["status", "updated_at"])
+ return Response(
+ {
+ "id": str(batch_job.id),
+ "status": batch_job.status,
+ "no_op": False,
+ }
+ )
+ except Exception as e:
+ logger.exception(
+ "Error in internal_update_batch_job_status",
+ error=str(e),
+ team_id=team_id,
+ batch_job_id=batch_job_id,
+ )
+ return Response({"error": "Internal server error"}, status=500)
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 5fd6f24b3adb..e8610d44ea94 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -22,6 +22,7 @@ from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_
from products.cohorts.backend.models.cohort import Cohort
from products.workflows.backend.api.hog_flow import _should_validate_strictly
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob
webhook_template = MOCK_NODE_TEMPLATES[0]
@@ -2037,6 +2038,108 @@ class TestHogFlowAPI(APIBaseTest):
assert "Feature flags can't be used as a batch audience condition" in response.json().get("error", "")
mock_get_user_blast_radius_persons.assert_not_called()
+ @override_settings(INTERNAL_API_SECRET="test-secret-123")
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_internal_update_batch_job_status_marks_completed(self, _mock_dispatch):
+ hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=hog_flow, status="active")
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/{batch_job.id}/status",
+ {"status": "completed"},
+ content_type="application/json",
+ headers={"x-internal-api-secret": "test-secret-123"},
+ )
+
+ assert response.status_code == 200, response.json()
+ assert response.json()["status"] == "completed"
+ assert response.json()["no_op"] is False
+ batch_job.refresh_from_db()
+ assert batch_job.status == "completed"
+
+ @override_settings(INTERNAL_API_SECRET="test-secret-123")
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_internal_update_batch_job_status_is_idempotent_when_already_terminal(self, _mock_dispatch):
+ hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=hog_flow, status="completed")
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/{batch_job.id}/status",
+ {"status": "failed"},
+ content_type="application/json",
+ headers={"x-internal-api-secret": "test-secret-123"},
+ )
+
+ # Already terminal → no-op, original status preserved
+ assert response.status_code == 200, response.json()
+ assert response.json()["no_op"] is True
+ assert response.json()["status"] == "completed"
+ batch_job.refresh_from_db()
+ assert batch_job.status == "completed"
+
+ @override_settings(INTERNAL_API_SECRET="test-secret-123")
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_internal_update_batch_job_status_rejects_invalid_status(self, _mock_dispatch):
+ hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=hog_flow, status="active")
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/{batch_job.id}/status",
+ {"status": "active"}, # not a terminal state
+ content_type="application/json",
+ headers={"x-internal-api-secret": "test-secret-123"},
+ )
+
+ assert response.status_code == 400, response.json()
+ batch_job.refresh_from_db()
+ assert batch_job.status == "active" # unchanged
+
+ @override_settings(INTERNAL_API_SECRET="test-secret-123")
+ def test_internal_update_batch_job_status_returns_404_for_missing_job(self):
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/00000000-0000-0000-0000-000000000000/status",
+ {"status": "completed"},
+ content_type="application/json",
+ headers={"x-internal-api-secret": "test-secret-123"},
+ )
+
+ assert response.status_code == 404, response.json()
+
+ @override_settings(INTERNAL_API_SECRET="test-secret-123")
+ def test_internal_update_batch_job_status_returns_404_for_invalid_uuid(self):
+ # `not-a-uuid` reaches UUIDField → ValidationError, must surface as 404 not 500.
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/not-a-uuid/status",
+ {"status": "completed"},
+ content_type="application/json",
+ headers={"x-internal-api-secret": "test-secret-123"},
+ )
+
+ assert response.status_code == 404, response.json()
+
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_internal_update_batch_job_status_requires_internal_api_secret(self, _mock_dispatch):
+ hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+ batch_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=hog_flow, status="active")
+
+ # No INTERNAL_API_SECRET header → unauthenticated
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/internal/hog_flows/batch_jobs/{batch_job.id}/status",
+ {"status": "completed"},
+ content_type="application/json",
+ )
+
+ # Endpoint requires internal auth — anything other than 200 is acceptable
+ assert response.status_code in (401, 403), response.json()
+
def test_billable_action_types_computed_correctly(self):
"""Test that billable_action_types is computed correctly and cannot be overridden by clients"""
trigger_action = {
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index f477f6acfd17..87fc2264ff8d 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -660,6 +660,29 @@ export const hogFlowsUserBlastRadiusCreate = async (
})
}
+export const getInternalHogFlowsBatchJobsStatusUpdateUrl = (teamId: string, batchJobId: string) => {
+ return `/api/projects/${teamId}/internal/hog_flows/batch_jobs/${batchJobId}/status`
+}
+
+/**
+ * Internal endpoint for the Node-side batch resolver to write the terminal
+ * status of a HogFlowBatchJob run. Idempotent: if the row is already in a
+ * terminal status, returns 200 without re-writing — the resolver retries
+ * this call via cyclotron retry semantics, so safe repeats are required.
+ *
+ * Accepts: { status: "completed" | "failed" }
+ */
+export const internalHogFlowsBatchJobsStatusUpdate = async (
+ teamId: string,
+ batchJobId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getInternalHogFlowsBatchJobsStatusUpdateUrl(teamId, batchJobId), {
+ ...options,
+ method: 'PUT',
+ })
+}
+
export const getInternalHogFlowsUserBlastRadiusCreateUrl = (teamId: string) => {
return `/api/projects/${teamId}/internal/hog_flows/user_blast_radius`
}
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index d4d40fbeb5bf..3eddc83cb590 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -72,6 +72,9 @@ tools:
hog-flows-user-blast-radius-create:
operation: hog_flows_user_blast_radius_create
enabled: false
+ internal-hog-flows-batch-jobs-status-update:
+ operation: internal_hog_flows_batch_jobs_status_update
+ enabled: false
internal-hog-flows-process-due-schedules-create:
operation: internal_hog_flows_process_due_schedules_create
enabled: false