:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): count consumer loop errors per queue (#98274)
Meikel Ratze423dd2b79e7
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex 2fcffebbe0ea..e62211c37b62 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -14,7 +14,7 @@ import {CyclotronV2DequeuedJob,CyclotronV2JobInit,} from './types'-import { CyclotronV2Worker } from './worker'+import { CyclotronV2Worker, sleep } from './worker'import { CyclotronV2RateLimitedWorker } from './worker-rate-limited'const DB_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'@@ -172,6 +172,12 @@ async function gaugeValueForQueue(queue: string): Promise<number | null> {}// Absent until the queue's first churning dequeue, so a missing line reads as 0.+async function loopErrorCountForQueue(queue: string): Promise<number> {+ const metric = await register.getSingleMetricAsString('cdp_cyclotron_v2_consumer_loop_errors_total')+ const line = metric.split('\n').find((l) => l.includes(`queue="${queue}"`))+ return line ? Number(line.trim().split(' ').pop()) : 0+}+async function churnCountForQueue(queue: string): Promise<number> {const metric = await register.getSingleMetricAsString('cdp_cyclotron_v2_high_transition_dequeues')const line = metric.split('\n').find((l) => l.includes(`queue="${queue}"`))@@ -1023,6 +1029,50 @@ describe('Cyclotron V2', () => {expect(await countByStatus('running')).toBe(2)})+ // The loop swallows errors and retries, so a queue whose batches all throw looks+ // exactly like an idle queue. The counter is the only externally visible signal.+ it.each([+ ['the plain worker', 'loop-errors-plain', (): CyclotronV2Worker => createWorker('loop-errors-plain')],+ [+ 'the rate-limited worker',+ 'loop-errors-limited',+ (): CyclotronV2Worker =>+ new CyclotronV2RateLimitedWorker(+ {+ pool: { dbUrl: DB_URL },+ queueName: 'loop-errors-limited',+ batchMaxSize: 100,+ pollDelayMs: 10,+ },+ () => Promise.resolve(undefined)+ ),+ ],+ ])('counts a consumer loop error in %s', async (_name, queue, makeWorker) => {+ await manager.createJob({ teamId: 1, queueName: queue })+ const before = await loopErrorCountForQueue(queue)+ const worker = makeWorker()++ let threw = false+ await new Promise<void>((resolve) => {+ void worker.connect(async (batch) => {+ if (batch.length > 0 && !threw) {+ threw = true+ resolve()+ return Promise.reject(new Error('processing failed'))+ }+ })+ })+ // The throw resolves the promise before the loop's catch runs; give the+ // catch a moment to record it before stopping the loop.+ const deadline = Date.now() + 2_000+ while ((await loopErrorCountForQueue(queue)) - before < 1 && Date.now() < deadline) {+ await sleep(25)+ }+ await worker.stopConsuming()++ expect((await loopErrorCountForQueue(queue)) - before).toBe(1)+ })+// Both dequeue paths bump transition_count for the whole batch in one UPDATE, so an// unclamped increment on a saturated row aborts the statement and stops every job on// the queue, not just the saturated one. 'email' selects the fair path, a separatediff --git a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.tsindex 30d729bd506e..fac495168a1c 100644--- a/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/worker-rate-limited.ts@@ -2,7 +2,7 @@ import { logger } from '~/common/utils/logger'import { CyclotronV2BatchLimit, CyclotronV2WorkerConfig } from './types'import { CyclotronV2DequeuedJob } from './types'-import { CyclotronV2Worker, sleep } from './worker'+import { CyclotronV2Worker, consumerLoopErrorsCounter, sleep } from './worker'/*** Variant of CyclotronV2Worker that consults a per-poll rate-limit hook before@@ -69,6 +69,7 @@ export class CyclotronV2RateLimitedWorker extends CyclotronV2Worker {const jobs = rows.map((row) => this.wrapJob(row))await processBatch(jobs)} catch (err) {+ consumerLoopErrorsCounter.labels({ queue: this.queueName }).inc()logger.error('CyclotronV2RateLimitedWorker consumer loop error', { error: String(err) })await sleep(this.pollDelayMs)}diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.tsindex 4d11c935842c..3fbcfe037002 100644--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts@@ -43,6 +43,15 @@ const highTransitionDequeuesCounter = new Counter({labelNames: ['queue'] as const,})+// The loop swallows the error and retries, so without this counter a queue whose every+// dequeue throws looks exactly like an idle queue. Exported for the rate-limited+// subclass, which has its own loop and catch.+export const consumerLoopErrorsCounter = new Counter({+ name: 'cdp_cyclotron_v2_consumer_loop_errors_total',+ help: 'Consumer loop iterations that threw, per queue. A sustained positive rate can indicate the queue is not being consumed.',+ labelNames: ['queue'] as const,+})+export function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms))}@@ -218,6 +227,7 @@ export class CyclotronV2Worker {protected lastPollTime = new Date()private consumerLoopPromise: Promise<void> | null = null+ protected readonly queueName: stringprotected readonly batchMaxSize: numberprotected readonly pollDelayMs: numberprivate readonly heartbeatTimeoutMs: number@@ -230,6 +240,7 @@ export class CyclotronV2Worker {max: config.pool.maxConnections ?? 10,idleTimeoutMillis: config.pool.idleTimeoutMs ?? 30000,})+ this.queueName = config.queueNamethis.batchMaxSize = config.batchMaxSize ?? 100this.pollDelayMs = config.pollDelayMs ?? 50this.heartbeatTimeoutMs = config.heartbeatTimeoutMs ?? 30000@@ -266,6 +277,7 @@ export class CyclotronV2Worker {const jobs = rows.map((row) => this.wrapJob(row))await processBatch(jobs)} catch (err) {+ consumerLoopErrorsCounter.labels({ queue: this.queueName }).inc()logger.error('CyclotronV2Worker consumer loop error', { error: String(err) })await sleep(this.pollDelayMs)}