:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): heartbeat cyclotron v2 jobs during batch processing (#70400)
Meikel Ratz5045c61b5ab5
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex c3ab8ceb5bfc..0e2bd33bc3c7 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -56,6 +56,7 @@ export type CdpConfig = ClickhouseConfig & {CDP_LEGACY_EVENT_CONSUMER_INCLUDE_WEBHOOKS: booleanCDP_CYCLOTRON_BATCH_DELAY_MS: number+ CDP_CYCLOTRON_HEARTBEAT_INTERVAL_MS: numberCDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE: numberCDP_CYCLOTRON_INSERT_PARALLEL_BATCHES: booleanCDP_CYCLOTRON_COMPRESS_VM_STATE: boolean@@ -181,6 +182,7 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_LEGACY_EVENT_CONSUMER_INCLUDE_WEBHOOKS: false,CDP_CYCLOTRON_BATCH_DELAY_MS: 50,+ CDP_CYCLOTRON_HEARTBEAT_INTERVAL_MS: 10000,CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE: 100,CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES: true,CDP_CYCLOTRON_COMPRESS_VM_STATE: isProdEnv() ? false : true,diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.tsindex f0318718a72c..b6f91e69ade6 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts@@ -132,14 +132,38 @@ export class CdpCyclotronWorker<size: invocations.length,})- const invocationResults = await this.processInvocations(invocations)+ // Heartbeat until the background task settles — the tail includes+ // queueInvocationResults' terminal DB writes, which is where a slow+ // batch would otherwise blow past stallTimeoutMs and get poisoned.+ const stopHeartbeat = this.startPeriodicHeartbeat(invocations)++ let invocationResults: CyclotronJobInvocationResult[]+ try {+ invocationResults = await this.processInvocations(invocations)+ } catch (e) {+ stopHeartbeat()+ throw e+ }// NOTE: We can queue and publish all metrics in the background whilst processing the next batch of invocations- const backgroundTask = this.runBackgroundTasks(invocationResults)+ const backgroundTask = this.runBackgroundTasks(invocationResults).finally(stopHeartbeat)return { backgroundTask, invocationResults }}+ private startPeriodicHeartbeat(invocations: CyclotronJobInvocation[]): () => void {+ const intervalMs = this.config.CDP_CYCLOTRON_HEARTBEAT_INTERVAL_MS+ if (intervalMs <= 0) {+ return () => {}+ }+ const handle = setInterval(() => {+ void this.cyclotronJobQueue.heartbeatInvocations(invocations).catch((err) => {+ logger.warn('⚠️', `${this.name} - heartbeat tick failed`, { error: String(err) })+ })+ }, intervalMs)+ return () => clearInterval(handle)+ }+@instrumented({ key: 'cdpConsumer.backgroundTask', timeoutMs: 30_000, sendException: false })private async runBackgroundTasks(invocationResults: CyclotronJobInvocationResult[]): Promise<void> {await this.queueInvocationResults(invocationResults)diff --git a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts b/nodejs/src/cdp/services/job-queue/job-queue-kafka.tsindex f85cd1330dcb..6ad38d1c2559 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts@@ -143,6 +143,7 @@ export class CyclotronJobQueueKafka implements JobQueue {// Kafka jobs don't need explicit dequeue/cancel — they're just droppedpublic async dequeueInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}public async cancelInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}+ public async heartbeatInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {// With kafka we are essentially re-queuing the work to the target topic if it isn't finisheddiff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.tsindex e3c30363cb8d..a7655ce2fcb4 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts@@ -352,4 +352,45 @@ describe('CyclotronJobQueuePostgresV2', () => {expect((queue as any).pendingJobs.has(job.id)).toBe(false)})})++ describe('heartbeatInvocations', () => {+ it('proxies to heartbeat, skips unknown ids, and distinguishes released races from real failures', async () => {+ const { queue } = createQueue()+ const warnSpy = jest.spyOn(require('~/common/utils/logger').logger, 'warn').mockImplementation(() => {})++ const pending = createDequeuedJob()+ const released = createDequeuedJob({+ heartbeat: jest.fn().mockRejectedValue(new Error(`Job ${'x'} already released, cannot heartbeat`)),+ })+ const brokenPg = createDequeuedJob({+ heartbeat: jest.fn().mockRejectedValue(new Error('Connection terminated unexpectedly')),+ })+ ;(queue as any).pendingJobs.set(pending.id, pending)+ ;(queue as any).pendingJobs.set(released.id, released)+ ;(queue as any).pendingJobs.set(brokenPg.id, brokenPg)++ await expect(+ queue.heartbeatInvocations([+ { ...baseInvocation, id: pending.id },+ { ...baseInvocation, id: released.id },+ { ...baseInvocation, id: brokenPg.id },+ { ...baseInvocation, id: uuidv4() }, // not in pendingJobs+ ])+ ).resolves.toBeUndefined()++ expect(pending.heartbeat).toHaveBeenCalledTimes(1)+ expect(released.heartbeat).toHaveBeenCalledTimes(1)+ expect(brokenPg.heartbeat).toHaveBeenCalledTimes(1)+ // released-race stays quiet (debug), real Postgres failure gets a warn+ expect(warnSpy).toHaveBeenCalledTimes(1)+ expect(warnSpy).toHaveBeenCalledWith(+ 'CyclotronV2 heartbeat failed',+ expect.objectContaining({ error: 'Connection terminated unexpectedly' })+ )+ // pendingJobs is unchanged — heartbeat is not a terminal transition+ expect((queue as any).pendingJobs.size).toBe(3)++ warnSpy.mockRestore()+ })+ })})diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.tsindex e774abac79e1..d72ecf6fdc52 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@@ -261,6 +261,32 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {}))}++ public async heartbeatInvocations(invocations: CyclotronJobInvocation[]): Promise<void> {+ await Promise.all(+ invocations.map(async (inv) => {+ const job = this.pendingJobs.get(inv.id)+ if (!job) {+ return+ }+ try {+ await job.heartbeat()+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ if (message.includes('already released')) {+ // Benign race with ack/fail/reschedule flipping `released` on the wrapper.+ logger.debug('CyclotronV2 heartbeat skipped for released job', { id: inv.id })+ } else {+ // Real failure (connection error, pool exhaustion, query timeout) —+ // surface it so we can act. Don't rethrow: the tick continues for+ // the other jobs and the interval keeps firing so a transient blip+ // doesn't kill the batch.+ logger.warn('CyclotronV2 heartbeat failed', { id: inv.id, error: message })+ }+ }+ })+ )+ }}function serializeState(invocation: CyclotronJobInvocation): Buffer {diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres.tsindex 748abdfb7c7c..339b12c50e91 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres.ts@@ -208,6 +208,9 @@ export class CyclotronJobQueuePostgres implements JobQueue {)}+ // 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 kafkaconst worker = this.getCyclotronWorker()diff --git a/nodejs/src/cdp/services/job-queue/job-queue.interface.ts b/nodejs/src/cdp/services/job-queue/job-queue.interface.tsindex f7ba70b5f07d..63802bd3ff23 100644--- a/nodejs/src/cdp/services/job-queue/job-queue.interface.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue.interface.ts@@ -17,4 +17,5 @@ export interface JobQueue {queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void>dequeueInvocations(invocations: CyclotronJobInvocation[]): Promise<void>cancelInvocations(invocations: CyclotronJobInvocation[]): Promise<void>+ heartbeatInvocations(invocations: CyclotronJobInvocation[]): Promise<void>}diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 84a0220f9091..21dd677dd41f 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -50,7 +50,7 @@ import { CdpCyclotronWorkerHogFlow } from './consumers/cdp-cyclotron-worker-hogfimport { 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 { CyclotronV2Janitor, CyclotronV2Manager, CyclotronV2Worker } from './services/cyclotron-v2'import {HOGFLOW_BATCH_RESOLVE_QUEUE,MAX_RESOLVER_ATTEMPTS,@@ -1690,6 +1690,102 @@ 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,+ })++ 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+ )+ )+ )++ 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.+ 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 jobsdiff --git a/nodejs/tests/helpers/mocks/job-queue.mock.ts b/nodejs/tests/helpers/mocks/job-queue.mock.tsindex a3d1c73e3885..a82ce75d7ad3 100644--- a/nodejs/tests/helpers/mocks/job-queue.mock.ts+++ b/nodejs/tests/helpers/mocks/job-queue.mock.ts@@ -11,5 +11,6 @@ export function createMockJobQueue(): jest.Mocked<JobQueue> {isHealthy: jest.fn(),dequeueInvocations: jest.fn().mockResolvedValue(undefined),cancelInvocations: jest.fn().mockResolvedValue(undefined),+ heartbeatInvocations: jest.fn().mockResolvedValue(undefined),} as jest.Mocked<JobQueue>}