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.

chore(cdp): remove cyclotron v1 legacy-pg drain workers and v1 queue backend (#78160)

Daniel Marchukb351525d76e1
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 439eb3b1b410..e111f14b4cae 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -127,18 +127,10 @@ export function getPluginServerCapabilities(
return {
cdpCyclotronWorkerHogFlow: true,
}
- case PluginServerMode.cdp_cyclotron_worker_hogflow_legacy_pg:
- return {
- cdpCyclotronWorkerHogFlowLegacyPg: true,
- }
case PluginServerMode.cdp_cyclotron_worker_email:
return {
cdpCyclotronWorkerEmail: true,
}
- case PluginServerMode.cdp_cyclotron_worker_email_legacy_pg:
- return {
- cdpCyclotronWorkerEmailLegacyPg: true,
- }
case PluginServerMode.cdp_precalculated_filters:
// The consumer is gone. Boot with no capabilities so a pod that charts still
// launches in this mode idles instead of crash-looping on an unknown mode.
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres.test.ts
deleted file mode 100644
index 9af97edc2808..000000000000
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { v4 as uuidv4 } from 'uuid'
-
-import { CyclotronJobQueuePostgres } from './job-queue-postgres'
-
-// Mock external dependency to avoid needing the actual implementation in tests
-jest.mock('@posthog/cyclotron', () => ({
- CyclotronManager: jest.fn(),
- CyclotronWorker: jest.fn(),
-}))
-
-describe('CyclotronJobQueue - postgres', () => {
- function createQueue() {
- const config: any = {
- CYCLOTRON_DATABASE_URL: 'postgres://test',
- CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE: 1000,
- CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES: false,
- }
- const queue = new CyclotronJobQueuePostgres(500, config)
-
- const bulkCreateJobs = jest.fn().mockResolvedValue(undefined)
- // Inject a fake manager so queueInvocations can run without connecting
- ;(queue as any).cyclotronManager = {
- bulkCreateJobs,
- }
-
- return { queue, bulkCreateJobs }
- }
-
- describe('queueInvocations - isValidUuid behavior', () => {
- const baseInvocation = {
- teamId: 1,
- functionId: '0196a6b9-1104-0000-f099-9cf11985a307',
- queue: 'hog',
- queuePriority: 0,
- state: {
- globals: {},
- timings: [],
- vmState: { bytecodes: {}, stack: [], upvalues: [] },
- },
- }
-
- it('preserves id when it is a valid UUID', async () => {
- const { queue, bulkCreateJobs } = createQueue()
-
- const invocation: any = {
- ...baseInvocation,
- id: uuidv4(),
- }
-
- await queue.queueInvocations([invocation])
-
- expect(bulkCreateJobs).toHaveBeenCalledTimes(1)
- const jobsArg = bulkCreateJobs.mock.calls[0][0]
- expect(Array.isArray(jobsArg)).toBe(true)
- expect(jobsArg).toHaveLength(1)
- expect(jobsArg[0].id).toBe(invocation.id)
- })
-
- it('omits id when it is NOT a valid UUID (string)', async () => {
- const { queue, bulkCreateJobs } = createQueue()
-
- const invocation: any = {
- ...baseInvocation,
- id: '123',
- }
-
- await queue.queueInvocations([invocation])
-
- const jobsArg = bulkCreateJobs.mock.calls[0][0]
- expect(jobsArg[0].id).toBeUndefined()
- })
-
- it('omits id when it is NOT a valid UUID (number)', async () => {
- const { queue, bulkCreateJobs } = createQueue()
-
- const invocation: any = {
- ...baseInvocation,
- id: 12345,
- }
-
- await queue.queueInvocations([invocation])
-
- const jobsArg = bulkCreateJobs.mock.calls[0][0]
- expect(jobsArg[0].id).toBeUndefined()
- })
- })
-})
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts
deleted file mode 100644
index 339b12c50e91..000000000000
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-/**
- * NOTE: We are often experimenting with different job queue implementations.
- * To make this easier this class is designed to abstract the queue as much as possible from
- * the underlying implementation.
- */
-import { chunk } from 'lodash'
-import { DateTime } from 'luxon'
-import { validate as isUuid } from 'uuid'
-
-import {
- CyclotronJob,
- CyclotronJobInit,
- CyclotronJobUpdate,
- CyclotronManager,
- CyclotronWorker,
-} from '@posthog/cyclotron'
-
-import { CyclotronInvocationQueueParametersType } from '~/cdp/schema/cyclotron'
-import { logger } from '~/common/utils/logger'
-import { captureException } from '~/common/utils/posthog'
-
-import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk } from '../../../types'
-import { CdpConfig } from '../../config'
-import { CyclotronJobInvocation, CyclotronJobInvocationResult, CyclotronJobQueueKind } from '../../types'
-import { JobQueue } from './job-queue.interface'
-import { createInvocationSanitizer, observeConsumedBatch } from './shared'
-
-/**
- * Legacy postgres v1 queue via @posthog/cyclotron.
- * Only kept for draining old jobs — no new jobs are produced to v1.
- * Delete this file once the legacy worker is shut down.
- */
-export class CyclotronJobQueuePostgres implements JobQueue {
- private cyclotronWorker?: CyclotronWorker
- private cyclotronManager?: CyclotronManager
- private queue?: CyclotronJobQueueKind
- private consumeBatch?: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>
- private sanitizer: ReturnType<typeof createInvocationSanitizer>
-
- constructor(
- private consumerBatchSize: number,
- private config: Pick<
- CdpConfig,
- | 'CYCLOTRON_DATABASE_URL'
- | 'CYCLOTRON_SHARD_DEPTH_LIMIT'
- | 'CDP_CYCLOTRON_COMPRESS_VM_STATE'
- | 'CDP_CYCLOTRON_USE_BULK_COPY_JOB'
- | 'CDP_CYCLOTRON_BATCH_DELAY_MS'
- | 'CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE'
- | 'CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES'
- | 'CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS'
- >
- ) {
- this.sanitizer = createInvocationSanitizer(config)
- }
-
- /**
- * Helper to only start the producer related code (e.g. when not a consumer)
- */
- public async startAsProducer() {
- if (this.cyclotronManager) {
- return
- }
- if (!this.config.CYCLOTRON_DATABASE_URL) {
- throw new Error('Cyclotron database URL not set! This is required for the CDP services to work.')
- }
-
- this.cyclotronManager = new CyclotronManager({
- shards: [
- {
- dbUrl: this.config.CYCLOTRON_DATABASE_URL,
- },
- ],
- shardDepthLimit: this.config.CYCLOTRON_SHARD_DEPTH_LIMIT ?? 1000000,
- shouldCompressVmState: this.config.CDP_CYCLOTRON_COMPRESS_VM_STATE,
- shouldUseBulkJobCopy: this.config.CDP_CYCLOTRON_USE_BULK_COPY_JOB,
- })
-
- await this.cyclotronManager.connect()
- }
-
- public async startAsConsumer(
- queue: CyclotronJobQueueKind,
- consumeBatch: (invocations: CyclotronJobInvocation[]) => Promise<{ backgroundTask: Promise<any> }>
- ) {
- this.queue = queue
- this.consumeBatch = consumeBatch
-
- if (!this.config.CYCLOTRON_DATABASE_URL) {
- throw new Error('Cyclotron database URL not set! This is required for the CDP services to work.')
- }
- // The consumer always needs the producers as well
- await this.startAsProducer()
-
- this.cyclotronWorker = new CyclotronWorker({
- pool: {
- dbUrl: this.config.CYCLOTRON_DATABASE_URL,
- },
- queueName: queue,
- includeVmState: true, // NOTE: We used to omit the vmstate but given we can requeue to kafka we need it
- batchMaxSize: this.consumerBatchSize, // Use the common value
- pollDelayMs: this.config.CDP_CYCLOTRON_BATCH_DELAY_MS,
- includeEmptyBatches: true,
- shouldCompressVmState: this.config.CDP_CYCLOTRON_COMPRESS_VM_STATE,
- })
- await this.cyclotronWorker.connect((jobs) => this.consumeCyclotronJobs(jobs))
- }
-
- public async stopConsumer() {
- await this.cyclotronWorker?.disconnect()
- }
-
- public async stopProducer() {
- // NOTE: Currently doesn't do anything as there is no disconnect logic - just keeps the interfaces the same
- return Promise.resolve()
- }
-
- public isHealthy(): HealthCheckResult {
- try {
- const worker = this.getCyclotronWorker()
- const isHealthy = worker.isHealthy()
- if (isHealthy) {
- return new HealthCheckResultOk()
- } else {
- return new HealthCheckResultError('Cyclotron worker is not healthy', {})
- }
- } catch (error) {
- return new HealthCheckResultError('Cyclotron worker not initialized', {
- error: error instanceof Error ? error.message : String(error),
- })
- }
- }
-
- public async queueInvocations(invocations: CyclotronJobInvocation[]) {
- if (invocations.length === 0) {
- return
- }
-
- invocations = this.sanitizer.sanitizeInvocations(invocations)
-
- const cyclotronManager = this.getCyclotronManager()
-
- // For the cyclotron ones we simply create the jobs
- const cyclotronJobs = invocations.map((item) => invocationToCyclotronJobInitial(item))
-
- try {
- // Cyclotron batches inserts into one big INSERT which can lead to contention writing WAL information hence we chunk into batches
- const chunkedCyclotronJobs = chunk(cyclotronJobs, this.config.CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE)
-
- if (this.config.CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES) {
- // NOTE: It's not super clear the perf tradeoffs of doing this in parallel hence the config option
- await Promise.all(chunkedCyclotronJobs.map((jobs) => cyclotronManager.bulkCreateJobs(jobs)))
- } else {
- for (const jobs of chunkedCyclotronJobs) {
- await cyclotronManager.bulkCreateJobs(jobs)
- }
- }
- } catch (e) {
- logger.error('⚠️', 'Error creating cyclotron jobs', e)
- logger.warn('⚠️', 'Failed jobs', { jobs: cyclotronJobs })
- throw e
- }
- }
-
- public async dequeueInvocations(invocations: CyclotronJobInvocation[]) {
- const worker = this.getCyclotronWorker()
-
- await Promise.all(
- invocations.map((item) => {
- worker.updateJob(item.id, 'failed')
- return worker.releaseJob(item.id)
- })
- )
- }
-
- public async cancelInvocations(invocations: CyclotronJobInvocation[]) {
- const worker = this.getCyclotronWorker()
-
- await Promise.all(
- invocations.map((item) => {
- worker.updateJob(item.id, 'canceled')
- return worker.releaseJob(item.id)
- })
- )
- }
-
- public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {
- invocationResults = this.sanitizer.sanitizeResults(invocationResults)
- const worker = this.getCyclotronWorker()
- await Promise.all(
- invocationResults.map((item) => {
- const id = item.invocation.id
- if (item.error) {
- logger.debug('⚡️', 'Updating job to failed', id)
- worker.updateJob(id, 'failed')
- } else if (item.finished) {
- logger.debug('⚡️', 'Updating job to completed', id)
- worker.updateJob(id, 'completed')
- } else {
- logger.debug('⚡️', 'Updating job to available', id)
-
- const updates = invocationToCyclotronJobUpdate(item.invocation)
-
- worker.updateJob(id, 'available', updates)
- }
- return worker.releaseJob(id)
- })
- )
- }
-
- // Legacy V1 has no per-job heartbeat API; stall recovery works differently there.
- public async heartbeatInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}
-
- public async releaseInvocations(invocations: CyclotronJobInvocation[]) {
- // Called specially for jobs that came from postgres but are being requeued to kafka
- const worker = this.getCyclotronWorker()
- await Promise.all(
- invocations.map((item) => {
- const id = item.id
- logger.debug('⚡️', 'Releasing job', id)
- worker.updateJob(id, 'completed')
- return worker.releaseJob(id)
- })
- )
- }
-
- private getCyclotronWorker(): CyclotronWorker {
- if (!this.cyclotronWorker) {
- throw new Error('CyclotronWorker not initialized')
- }
- return this.cyclotronWorker
- }
-
- private getCyclotronManager(): CyclotronManager {
- if (!this.cyclotronManager) {
- throw new Error('CyclotronManager not initialized')
- }
- return this.cyclotronManager
- }
-
- private async consumeCyclotronJobs(jobs: CyclotronJob[]) {
- const invocations: CyclotronJobInvocation[] = []
- // A list of all the promises related to job releasing that we need to await
-
- for (const job of jobs) {
- const invocation = cyclotronJobToInvocation(job)
- invocations.push(invocation)
- }
-
- observeConsumedBatch({
- queue: this.queue!,
- source: 'postgres',
- batchSize: invocations.length,
- maxBatchSize: this.consumerBatchSize,
- })
-
- await this.consumeBatch!(invocations)
- // TODO: Ensure that all jobs eventually get acked!!!
- }
-}
-
-function invocationToCyclotronJobInitial(invocation: CyclotronJobInvocation): CyclotronJobInit {
- const queueParameters: CyclotronJobInvocation['queueParameters'] = invocation.queueParameters
- let blob: CyclotronJobInit['blob'] = null
- let parameters: CyclotronJobInit['parameters'] = null
-
- // TODO: Ditch this queue params stuff
- if (queueParameters) {
- if (queueParameters.type === 'fetch') {
- const { body, ...rest } = queueParameters
- parameters = rest
- blob = body ? Buffer.from(body) : null
- } else if (queueParameters.type === 'email') {
- parameters = queueParameters
- blob = null
- }
- }
-
- // Preserve the invocation id when inserting into Postgres so switching backends keeps the same ID
- // cyclotron db expects this to be a valid UUID
- const isValidUuid = typeof invocation.id === 'string' && isUuid(invocation.id)
-
- const job: CyclotronJobInit & { id?: string } = {
- id: isValidUuid ? invocation.id : undefined,
- teamId: invocation.teamId,
- functionId: invocation.functionId,
- queueName: invocation.queue,
- priority: invocation.queuePriority,
- parentRunId: invocation.parentRunId ?? null,
- vmState: invocation.state,
- parameters,
- blob,
- metadata: invocation.queueMetadata ?? null,
- scheduled: invocation.queueScheduledAt?.toISO() ?? DateTime.now().toISO(),
- }
- return job
-}
-
-function invocationToCyclotronJobUpdate(invocation: CyclotronJobInvocation): CyclotronJobUpdate {
- const job = invocationToCyclotronJobInitial(invocation)
- // Currently the job updates are identical to the initial job
- return job
-}
-
-function cyclotronJobToInvocation(job: CyclotronJob): CyclotronJobInvocation {
- const params = job.parameters as CyclotronInvocationQueueParametersType | undefined
-
- if (job.blob && params && params.type === 'fetch') {
- // Deserialize the blob into the params
- try {
- params.body = job.blob ? Buffer.from(job.blob).toString('utf-8') : undefined
- } catch (e) {
- logger.error('Error parsing blob', e, job.blob)
- captureException(e)
- }
- }
-
- const invocation: CyclotronJobInvocation = {
- id: job.id,
- state: job.vmState,
- teamId: job.teamId,
- functionId: job.functionId!, // TODO: Fix this in the underlying cyclotron library - it should never be nullable
- queue: job.queueName as CyclotronJobQueueKind,
- queuePriority: job.priority,
- queueScheduledAt: job.scheduled ? DateTime.fromISO(job.scheduled) : undefined,
- queueMetadata: job.metadata ?? undefined,
- queueParameters: params,
- queueSource: 'postgres', // NOTE: We always set this here, as we know it came from postgres
- }
-
- // Only add parentRunId if it exists (avoid adding undefined field)
- if (job.parentRunId) {
- invocation.parentRunId = job.parentRunId
- }
-
- return invocation
-}
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 12be70c7ebff..399726b3cf58 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -69,7 +69,6 @@ import {
} 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'
import { CyclotronJobQueueRateLimitedPostgresV2 } from './services/job-queue/job-queue-rate-limited-postgres-v2'
import { JobQueue } from './services/job-queue/job-queue.interface'
@@ -100,10 +99,8 @@ jest.mock('node:dns/promises', () => ({
// Use the same env vars as config.ts (lines 221-229) so cleanup pools and hub target the same DBs
const CYCLOTRON_NODE_DB_URL =
process.env.CYCLOTRON_NODE_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'
-const CYCLOTRON_DB_URL =
- process.env.CYCLOTRON_DATABASE_URL ?? 'postgres://posthog:posthog@localhost:5432/test_cyclotron'
-describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)', (mode) => {
+describe('Workflows E2E (postgres-v2)', () => {
jest.setTimeout(30000)
let eventsConsumer: CdpEventsConsumer
@@ -122,7 +119,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
beforeAll(() => {
cyclotronPool = new Pool({
- connectionString: mode === 'postgres-v2' ? CYCLOTRON_NODE_DB_URL : CYCLOTRON_DB_URL,
+ connectionString: CYCLOTRON_NODE_DB_URL,
})
})
@@ -177,12 +174,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)
- // Build the hogflow queue for the current mode
- if (mode === 'postgres-v2') {
- hogflowQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
- } else {
- hogflowQueue = new CyclotronJobQueuePostgres(hub.CONSUMER_BATCH_SIZE, hub)
- }
+ hogflowQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
// Events consumer — only start as producer (skip Kafka consumer connection).
// We call processBatch() directly so the Kafka consumer is not needed.
@@ -198,7 +190,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
await Promise.all([kafkaQueue.startAsProducer(), hogflowQueue.startAsProducer()])
- // Start hogflow worker (consumer side — polls from the mode's backend)
+ // Start hogflow worker (consumer side — polls the postgres-v2 backend)
hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, deps, hogflowQueue)
await hogflowWorker.start()
@@ -239,15 +231,11 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
}
- // v1 stores lifecycle in `state` (and vm payload in `vm_state`);
- // v2 stores lifecycle in `status` (and state payload in `state`).
- // Normalize so tests can use `.status` regardless of mode.
- const statusColumn = mode === 'postgres-v2' ? 'status' : 'state'
+ // v2 stores job lifecycle in the `status` column.
+ const statusColumn = 'status'
async function queryCyclotronJobs(): Promise<any[]> {
- const result = await cyclotronPool.query(
- `SELECT *, ${statusColumn} AS status FROM cyclotron_jobs ORDER BY created ASC`
- )
+ const result = await cyclotronPool.query(`SELECT * FROM cyclotron_jobs ORDER BY created ASC`)
return result.rows
}
@@ -903,11 +891,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
})
- // The matcher reads parked jobs via `CYCLOTRON_NODE_DATABASE_URL` (the postgres-v2 backend).
- // In legacy `postgres` mode the worker parks the job in a different DB the matcher cannot see,
- // so wakes are postgres-v2-only.
- const describeMatcher = mode === 'postgres-v2' ? describe : describe.skip
- describeMatcher('wait_until_condition: subscription matcher wakes parked jobs', () => {
+ describe('wait_until_condition: subscription matcher wakes parked jobs', () => {
let matcher: CdpHogflowSubscriptionMatcherConsumer
// trigger → wait_condition → (matched branch | timeout continue) → exit
@@ -2222,106 +2206,100 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
})
- // Heartbeat + janitor is postgres-v2-only. Skipping on the legacy postgres
- // mode where the heartbeat wrapper is a no-op.
- if (mode === 'postgres-v2') {
- describe('heartbeat during long batches', () => {
- let janitor: CyclotronV2Janitor
-
- beforeEach(async () => {
- // Restart the worker with a short heartbeat interval so the
- // interval fires several times inside the test's ~1s fetch delay.
- // Default is 10s — nothing would fire in a test.
- await hogflowWorker.stop()
- hub.CDP_CYCLOTRON_HEARTBEAT_INTERVAL_MS = 100
- hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, deps, hogflowQueue)
- await hogflowWorker.start()
-
- // Aggressive stall/poison thresholds so the test observes the
- // exact regression the heartbeat guards against: without heartbeats
- // firing, a 1.2s fetch would exceed the 300ms stall window and
- // the janitor would reset the row on the very first runOnce().
- // cleanupGraceMs is huge so terminal jobs stay queryable after
- // completion — we assert on their final janitor_touch_count.
- janitor = new CyclotronV2Janitor({
- pool: { dbUrl: CYCLOTRON_NODE_DB_URL },
- stallTimeoutMs: 300,
- maxTouchCount: 2,
- cleanupGraceMs: 99_999_000,
- cleanupBatchSize: 100,
- cleanupIntervalMs: 60_000,
- })
+ describe('heartbeat during long batches', () => {
+ let janitor: CyclotronV2Janitor
- await createWorkflow({
- actions: {
- trigger: trigger(),
- slow_fetch: fetchAction('https://example.com/slow'),
- exit: exitAction(),
- },
- edges: [
- { from: 'trigger', to: 'slow_fetch', type: 'continue' },
- { from: 'slow_fetch', to: 'exit', type: 'continue' },
- ],
- })
- globals = createGlobals()
+ beforeEach(async () => {
+ // Restart the worker with a short heartbeat interval so the
+ // interval fires several times inside the test's ~1s fetch delay.
+ // Default is 10s — nothing would fire in a test.
+ await hogflowWorker.stop()
+ hub.CDP_CYCLOTRON_HEARTBEAT_INTERVAL_MS = 100
+ hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, deps, hogflowQueue)
+ await hogflowWorker.start()
+
+ // Aggressive stall/poison thresholds so the test observes the
+ // exact regression the heartbeat guards against: without heartbeats
+ // firing, a 1.2s fetch would exceed the 300ms stall window and
+ // the janitor would reset the row on the very first runOnce().
+ // cleanupGraceMs is huge so terminal jobs stay queryable after
+ // completion — we assert on their final janitor_touch_count.
+ janitor = new CyclotronV2Janitor({
+ pool: { dbUrl: CYCLOTRON_NODE_DB_URL },
+ stallTimeoutMs: 300,
+ maxTouchCount: 2,
+ cleanupGraceMs: 99_999_000,
+ cleanupBatchSize: 100,
+ cleanupIntervalMs: 60_000,
})
- afterEach(async () => {
- await janitor?.stop()
+ await createWorkflow({
+ actions: {
+ trigger: trigger(),
+ slow_fetch: fetchAction('https://example.com/slow'),
+ exit: exitAction(),
+ },
+ edges: [
+ { from: 'trigger', to: 'slow_fetch', type: 'continue' },
+ { from: 'slow_fetch', to: 'exit', type: 'continue' },
+ ],
})
+ globals = createGlobals()
+ })
+
+ afterEach(async () => {
+ await janitor?.stop()
+ })
- it('heartbeats keep janitor_touch_count at 0 during a slow batch', async () => {
- // Fetch takes 1.2s — 4x the stallTimeoutMs. The heartbeat
- // interval firing every 100ms is the only thing preventing
- // last_heartbeat from going stale.
- mockFetch.mockImplementation(
- () =>
- new Promise((resolve) =>
- setTimeout(
- () =>
- resolve({
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- json: () => Promise.resolve({ ok: true }),
- text: () => Promise.resolve(JSON.stringify({ ok: true })),
- dump: () => Promise.resolve(),
- }),
- 1200
- )
+ it('heartbeats keep janitor_touch_count at 0 during a slow batch', async () => {
+ // Fetch takes 1.2s — 4x the stallTimeoutMs. The heartbeat
+ // interval firing every 100ms is the only thing preventing
+ // last_heartbeat from going stale.
+ mockFetch.mockImplementation(
+ () =>
+ new Promise((resolve) =>
+ setTimeout(
+ () =>
+ resolve({
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ json: () => Promise.resolve({ ok: true }),
+ text: () => Promise.resolve(JSON.stringify({ ok: true })),
+ dump: () => Promise.resolve(),
+ }),
+ 1200
)
- )
+ )
+ )
+
+ await triggerWorkflow(globals)
+
+ // Wait long enough for the worker to dequeue and start the fetch,
+ // then check the janitor mid-flight. Without heartbeats,
+ // last_heartbeat would be ~700ms old (> 300ms cutoff) → stalled.
+ await new Promise((r) => setTimeout(r, 700))
+ const midResult = await janitor.runOnce()
+ expect(midResult.stalled).toBe(0)
+ expect(midResult.poisoned).toBe(0)
- await triggerWorkflow(globals)
-
- // Wait long enough for the worker to dequeue and start the fetch,
- // then check the janitor mid-flight. Without heartbeats,
- // last_heartbeat would be ~700ms old (> 300ms cutoff) → stalled.
- await new Promise((r) => setTimeout(r, 700))
- const midResult = await janitor.runOnce()
- expect(midResult.stalled).toBe(0)
- expect(midResult.poisoned).toBe(0)
-
- // Wait for the workflow to complete
- await waitForExpect(async () => {
- const jobs = await queryCyclotronJobs()
- expect(jobs.some((j) => j.status === 'completed')).toBe(true)
- }, 10000)
-
- // Final check: no row ever accumulated a touch. This is the
- // load-bearing assertion — regressions to the setInterval or
- // its cleanup would flip this to >= 1.
+ // Wait for the workflow to complete
+ await waitForExpect(async () => {
const jobs = await queryCyclotronJobs()
- for (const row of jobs) {
- expect(row.janitor_touch_count).toBe(0)
- }
- })
+ expect(jobs.some((j) => j.status === 'completed')).toBe(true)
+ }, 10000)
+
+ // Final check: no row ever accumulated a touch. This is the
+ // load-bearing assertion — regressions to the setInterval or
+ // its cleanup would flip this to >= 1.
+ const jobs = await queryCyclotronJobs()
+ for (const row of jobs) {
+ expect(row.janitor_touch_count).toBe(0)
+ }
})
- }
+ })
})
-// Email queue routing is postgres-v2 only — the email worker reschedules jobs
-// between queue names on the same v2 backend. We keep this block outside the
-// `describe.each` so the legacy postgres mode doesn't also try to exercise it.
+// Email queue routing: the email worker reschedules jobs between queue names on the same v2 backend.
describe('Workflows E2E (email queue)', () => {
jest.setTimeout(30000)
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 68f0ab6f3cb9..352422f6ffd7 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -37,9 +37,7 @@ export enum PluginServerMode {
cdp_hogflow_subscription_matcher = 'cdp-hogflow-subscription-matcher',
cdp_cohort_membership = 'cdp-cohort-membership',
cdp_cyclotron_worker_hogflow = 'cdp-cyclotron-worker-hogflow',
- cdp_cyclotron_worker_hogflow_legacy_pg = 'cdp-cyclotron-worker-hogflow-legacy-pg',
cdp_cyclotron_worker_email = 'cdp-cyclotron-worker-email',
- cdp_cyclotron_worker_email_legacy_pg = 'cdp-cyclotron-worker-email-legacy-pg',
cdp_api = 'cdp-api',
cdp_legacy_on_event = 'cdp-legacy-on-event',
evaluation_scheduler = 'evaluation-scheduler',
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 85047596ec19..8465fb97abbf 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -43,7 +43,6 @@ import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-
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'
import { CyclotronJobQueueRateLimitedPostgresV2 } from './cdp/services/job-queue/job-queue-rate-limited-postgres-v2'
import { hasEmailSigningKey } from './cdp/services/messaging/helpers/tracking-code'
@@ -99,9 +98,7 @@ export class PluginServer implements NodeServer {
capabilities.cdpApi ||
capabilities.cdpCyclotronWorker ||
capabilities.cdpCyclotronWorkerHogFlow ||
- capabilities.cdpCyclotronWorkerHogFlowLegacyPg ||
capabilities.cdpCyclotronWorkerEmail ||
- capabilities.cdpCyclotronWorkerEmailLegacyPg ||
capabilities.cdpCohortMembership ||
capabilities.cdpCyclotronWorkerBatchResolve ||
capabilities.cdpHogflowSubscriptionMatcher ||
@@ -318,24 +315,10 @@ export class PluginServer implements NodeServer {
})
}
- // Legacy postgres v1 drain for hogflow jobs — delete once cdp-cyclotron-worker-hogflows-pg-legacy is shut down
- if (capabilities.cdpCyclotronWorkerHogFlowLegacyPg) {
- serviceLoaders.push(async () => {
- const legacyQueue = new CyclotronJobQueuePostgres(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerHogFlow(
- this.config,
- this.withEmailValidationValkey(cdpDeps!),
- legacyQueue
- )
- await worker.start()
- return worker.service
- })
- }
-
// Boot-time guard: an email-sending deployment must carry a signing key, otherwise every send
// would either mint an unsigned tracking link or (now that generate() fails closed) fail. Refuse
- // to start instead of degrading silently. Both email workers below sign tracking codes.
- const isEmailWorker = capabilities.cdpCyclotronWorkerEmail || capabilities.cdpCyclotronWorkerEmailLegacyPg
+ // to start instead of degrading silently. The email worker below signs tracking codes.
+ const isEmailWorker = capabilities.cdpCyclotronWorkerEmail
if (isEmailWorker && !hasEmailSigningKey(this.config.ENCRYPTION_SALT_KEYS)) {
throw new Error(
'Email worker requires ENCRYPTION_SALT_KEYS to sign tracking codes — refusing to start. ' +
@@ -343,21 +326,6 @@ export class PluginServer implements NodeServer {
)
}
- // Transitional drain for email jobs stranded on the legacy V1 queue — the email worker
- // run against V1, sending inline. Delete once V1 'email' throughput is ~0.
- if (capabilities.cdpCyclotronWorkerEmailLegacyPg) {
- serviceLoaders.push(async () => {
- const legacyQueue = new CyclotronJobQueuePostgres(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerEmail(
- this.config,
- this.withEmailValidationValkey(cdpDeps!),
- legacyQueue
- )
- await worker.start()
- return worker.service
- })
- }
-
if (capabilities.cdpCyclotronWorkerEmail) {
serviceLoaders.push(async () => {
// Dedicated queue instance — see note on cdpCyclotronWorkerHogFlow above.
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index 07880732b1f1..d420507a41d1 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -145,9 +145,7 @@ export interface PluginServerCapabilities {
cdpCyclotronWorkerBatchResolve?: boolean
cdpCyclotronWorker?: boolean
cdpCyclotronWorkerHogFlow?: boolean
- cdpCyclotronWorkerHogFlowLegacyPg?: boolean
cdpCyclotronWorkerEmail?: boolean
- cdpCyclotronWorkerEmailLegacyPg?: boolean
cdpCohortMembership?: boolean
cdpApi?: boolean
appManagementSingleton?: boolean