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.

fix(cdp): saturate cyclotron job counters instead of overflowing (#97591)

Harley Alexander22dd52384170
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 e8cefbfdecdb..2fcffebbe0ea 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -7,7 +7,13 @@ import { parseJSON } from '~/common/utils/json-parse'
import { HogInvocationResultsService } from '../monitoring/hog-invocation-results.service'
import { CyclotronV2Janitor, JANITOR_POISON_PILL_ERROR_KIND } from './janitor'
import { CyclotronV2Manager } from './manager'
-import { CyclotronV2BatchLimit, CyclotronV2DequeuedJob, CyclotronV2JobInit } from './types'
+import {
+ CYCLOTRON_COUNTER_MAX,
+ CYCLOTRON_TRANSITION_CHURN_THRESHOLD,
+ CyclotronV2BatchLimit,
+ CyclotronV2DequeuedJob,
+ CyclotronV2JobInit,
+} from './types'
import { CyclotronV2Worker } from './worker'
import { CyclotronV2RateLimitedWorker } from './worker-rate-limited'
@@ -165,6 +171,13 @@ async function gaugeValueForQueue(queue: string): Promise<number | null> {
return line ? Number(line.trim().split(' ').pop()) : null
}
+// Absent until the queue's first churning dequeue, so a missing line reads as 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}"`))
+ return line ? Number(line.trim().split(' ').pop()) : 0
+}
+
describe('Cyclotron V2', () => {
jest.setTimeout(3000)
// Declared here, assigned in beforeAll
@@ -682,6 +695,24 @@ describe('Cyclotron V2', () => {
expect(row.transition_count).toBeGreaterThan(0)
})
+ it('createJob with overwriteExisting=true reruns a row whose transition_count is at the smallint ceiling', async () => {
+ const id = uuidv7()
+ await manager.createJob({ id, teamId: 1, queueName: QUEUE })
+ const worker = createWorker()
+ const jobs = await dequeueOneBatch(worker)
+ await jobs[0].ack()
+ await assertPool.query('UPDATE cyclotron_jobs SET transition_count = $1 WHERE id = $2', [
+ CYCLOTRON_COUNTER_MAX,
+ id,
+ ])
+
+ await manager.createJob({ id, teamId: 1, queueName: QUEUE, overwriteExisting: true })
+
+ const row = await queryJob(id)
+ expect(row.status).toBe('available')
+ expect(row.transition_count).toBe(CYCLOTRON_COUNTER_MAX)
+ })
+
it('createJob with overwriteExisting=true on a never-seen id behaves like a normal insert', async () => {
const id = uuidv7()
await manager.createJob({
@@ -992,6 +1023,49 @@ describe('Cyclotron V2', () => {
expect(await countByStatus('running')).toBe(2)
})
+ // 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 separate
+ // statement and the one the outage actually aborted.
+ it.each([
+ ['the plain dequeue', QUEUE],
+ ['the fair dequeue', 'email'],
+ ])('dequeues via %s alongside a job at the smallint ceiling', async (_label, queue) => {
+ // Backdate both so neither can miss the poll's `scheduled <= NOW()` window.
+ const scheduled = new Date(Date.now() - 60_000)
+ const saturated = await manager.createJob({ teamId: 1, queueName: queue, scheduled })
+ const healthy = await manager.createJob({ teamId: 1, queueName: queue, scheduled })
+ await assertPool.query('UPDATE cyclotron_jobs SET transition_count = $1 WHERE id = $2', [
+ CYCLOTRON_COUNTER_MAX,
+ saturated,
+ ])
+
+ const jobs = await dequeueOneBatch(createWorker(queue))
+
+ expect(jobs.map((j) => j.id).sort()).toEqual([saturated, healthy].sort())
+ const { rows } = await assertPool.query('SELECT transition_count FROM cyclotron_jobs WHERE id = $1', [
+ saturated,
+ ])
+ expect(rows[0].transition_count).toBe(CYCLOTRON_COUNTER_MAX)
+ })
+
+ // The loop that saturates a counter is claim, refuse, reschedule, so the release bumps
+ // it a second time per cycle and has to be clamped too.
+ it('reschedules a job at the smallint ceiling', async () => {
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE })
+ await assertPool.query('UPDATE cyclotron_jobs SET transition_count = $1 WHERE id = $2', [
+ CYCLOTRON_COUNTER_MAX,
+ id,
+ ])
+
+ const [job] = await dequeueOneBatch(createWorker())
+ await job.reschedule()
+
+ const row = await queryJob(id)
+ expect(row.status).toBe('available')
+ expect(row.transition_count).toBe(CYCLOTRON_COUNTER_MAX)
+ })
+
it('respects priority ordering (lower number = higher priority)', async () => {
await manager.createJob({ teamId: 1, queueName: QUEUE, priority: 2 })
await manager.createJob({ teamId: 1, queueName: QUEUE, priority: 0 })
@@ -1610,6 +1684,19 @@ describe('Cyclotron V2', () => {
const row = await queryJob(id)
expect(row.transition_count).toBe(1)
})
+
+ it.each([
+ ['below the churn threshold', CYCLOTRON_TRANSITION_CHURN_THRESHOLD - 2, 0],
+ ['at the churn threshold', CYCLOTRON_TRANSITION_CHURN_THRESHOLD - 1, 1],
+ ])('counts a dequeue %s', async (_label, seeded, expected) => {
+ const before = await churnCountForQueue(QUEUE)
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE })
+ await assertPool.query('UPDATE cyclotron_jobs SET transition_count = $1 WHERE id = $2', [seeded, id])
+
+ await dequeueOneBatch(createWorker())
+
+ expect((await churnCountForQueue(QUEUE)) - before).toBe(expected)
+ })
})
// ── Email fair dequeue ───────────────────────────────────────────
diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
index 4944e2916a3d..cd15867705f0 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
@@ -8,7 +8,12 @@ import { captureException } from '~/common/utils/posthog'
import { CYCLOTRON_INVOCATION_JOB_QUEUES, CyclotronJobInvocationHogFlow } from '../../types'
import { v2JobToInvocation } from '../job-queue/job-queue-postgres-v2'
import { HogInvocationResultsService } from '../monitoring/hog-invocation-results.service'
-import { CyclotronV2CleanupResult, CyclotronV2DequeuedJob, CyclotronV2JanitorConfig } from './types'
+import {
+ CYCLOTRON_COUNTER_MAX,
+ CyclotronV2CleanupResult,
+ CyclotronV2DequeuedJob,
+ CyclotronV2JanitorConfig,
+} from './types'
// Stable, low-cardinality `error_kind` stamped on the failed invocation result
// the janitor writes when it gives up on a poison pill. Lets operators target
@@ -238,7 +243,7 @@ export class CyclotronV2Janitor {
const result = await this.pool.query<{ id: string }>(
`UPDATE cyclotron_jobs
SET status = 'failed', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX})
WHERE id IN (
SELECT id
FROM cyclotron_jobs
@@ -470,7 +475,7 @@ export class CyclotronV2Janitor {
)
UPDATE cyclotron_jobs
SET status = 'available', lock_id = NULL, last_heartbeat = NULL,
- janitor_touch_count = janitor_touch_count + 1${backoffClause}
+ janitor_touch_count = LEAST(janitor_touch_count + 1, ${CYCLOTRON_COUNTER_MAX})${backoffClause}
FROM stalled
WHERE cyclotron_jobs.id = stalled.id`,
params
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index fc1c9a117f4f..969f2314a93a 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -7,6 +7,7 @@ import { logger } from '~/common/utils/logger'
import { sleep } from '~/common/utils/utils'
import {
+ CYCLOTRON_COUNTER_MAX,
CyclotronV2CancelJobsOptions,
CyclotronV2CancelJobsResult,
CyclotronV2InFlightCounts,
@@ -178,7 +179,7 @@ export class CyclotronV2Manager {
lock_id = NULL,
last_heartbeat = NULL,
last_transition = EXCLUDED.last_transition,
- transition_count = cyclotron_jobs.transition_count + 1,
+ transition_count = LEAST(cyclotron_jobs.transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
parent_run_id = EXCLUDED.parent_run_id,
state = EXCLUDED.state,
distinct_id = EXCLUDED.distinct_id,
@@ -286,7 +287,7 @@ export class CyclotronV2Manager {
lock_id = NULL,
last_heartbeat = NULL,
last_transition = EXCLUDED.last_transition,
- transition_count = cyclotron_jobs.transition_count + 1,
+ transition_count = LEAST(cyclotron_jobs.transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
parent_run_id = EXCLUDED.parent_run_id,
state = EXCLUDED.state,
distinct_id = EXCLUDED.distinct_id,
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index 4035d66edf0e..b9905ff957b8 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -3,6 +3,12 @@ import { z } from 'zod'
export type CyclotronV2JobStatus = 'available' | 'running' | 'completed' | 'failed' | 'canceled'
+// SMALLINT ceiling. Dequeue bumps the counter while claiming a batch, so one saturated row aborts the claim for every job in it.
+export const CYCLOTRON_COUNTER_MAX = 32767
+
+// Past this a job is in a retry loop it will not leave on its own. Set above normal work: live p99 is ~5k and the highest row ~19.5k.
+export const CYCLOTRON_TRANSITION_CHURN_THRESHOLD = 20000
+
export type CyclotronV2PoolConfig = {
dbUrl: string
maxConnections?: number
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index 298334329689..4d11c935842c 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -1,11 +1,14 @@
import { DateTime } from 'luxon'
import { Pool, PoolClient } from 'pg'
+import { Counter } from 'prom-client'
import { v7 as uuidv7 } from 'uuid'
import { logger } from '~/common/utils/logger'
import { assignEmailDequeueSeq } from './manager'
import {
+ CYCLOTRON_COUNTER_MAX,
+ CYCLOTRON_TRANSITION_CHURN_THRESHOLD,
CyclotronV2BulkCreateAndCheckInInput,
CyclotronV2DequeuedJob,
CyclotronV2JobInit,
@@ -33,6 +36,13 @@ export interface RawJobRow {
lock_id: string
}
+// Read off the row the dequeue already returns, so tracking churn costs no extra query.
+const highTransitionDequeuesCounter = new Counter({
+ name: 'cdp_cyclotron_v2_high_transition_dequeues',
+ help: `Jobs dequeued with transition_count at or above ${CYCLOTRON_TRANSITION_CHURN_THRESHOLD}, meaning they are cycling without completing.`,
+ labelNames: ['queue'] as const,
+})
+
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -148,7 +158,7 @@ async function updateSelfInTx(
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,
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
janitor_touch_count = 0
WHERE id = $1 AND lock_id = $2`,
[jobId, lockId]
@@ -160,7 +170,7 @@ async function updateSelfInTx(
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,
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
janitor_touch_count = 0
WHERE id = $1 AND lock_id = $2`,
[jobId, lockId]
@@ -175,7 +185,7 @@ async function updateSelfInTx(
`lock_id = NULL`,
`last_heartbeat = NULL`,
`last_transition = NOW()`,
- `transition_count = transition_count + 1`,
+ `transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX})`,
`janitor_touch_count = 0`,
// A cancel requested while this worker held the job must not sleep the full
// next delay before it's observed, so it wakes immediately instead.
@@ -310,7 +320,7 @@ export class CyclotronV2Worker {
lock_id = $3,
last_heartbeat = NOW(),
last_transition = NOW(),
- transition_count = transition_count + 1
+ transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX})
FROM available
WHERE cyclotron_jobs.id = available.id
RETURNING
@@ -374,7 +384,7 @@ export class CyclotronV2Worker {
lock_id = $3,
last_heartbeat = NOW(),
last_transition = NOW(),
- transition_count = transition_count + 1
+ transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX})
FROM available
WHERE cyclotron_jobs.id = available.id
RETURNING
@@ -408,6 +418,10 @@ export class CyclotronV2Worker {
const lockId = row.lock_id
let released = false
+ if (row.transition_count >= CYCLOTRON_TRANSITION_CHURN_THRESHOLD) {
+ highTransitionDequeuesCounter.labels({ queue: row.queue_name }).inc()
+ }
+
const releaseGuard = (method: string) => {
if (released) {
throw new Error(`Job ${row.id} already released, cannot call ${method}`)
@@ -438,7 +452,7 @@ export class CyclotronV2Worker {
await pool.query(
`UPDATE cyclotron_jobs
SET status = 'completed', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1,
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
janitor_touch_count = 0
WHERE id = $1 AND lock_id = $2`,
[row.id, lockId]
@@ -450,7 +464,7 @@ export class CyclotronV2Worker {
await pool.query(
`UPDATE cyclotron_jobs
SET status = 'failed', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1,
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
janitor_touch_count = 0
WHERE id = $1 AND lock_id = $2`,
[row.id, lockId]
@@ -467,7 +481,7 @@ export class CyclotronV2Worker {
`lock_id = NULL`,
`last_heartbeat = NULL`,
`last_transition = NOW()`,
- `transition_count = transition_count + 1`,
+ `transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX})`,
// A deliberate release means the worker is healthy, so the
// poison budget counts CONSECUTIVE stalls — long-lived jobs
// (e.g. wait_until_condition polls) don't accrue touches for
@@ -532,7 +546,7 @@ export class CyclotronV2Worker {
await pool.query(
`UPDATE cyclotron_jobs
SET status = 'canceled', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1,
+ last_transition = NOW(), transition_count = LEAST(transition_count + 1, ${CYCLOTRON_COUNTER_MAX}),
janitor_touch_count = 0
WHERE id = $1 AND lock_id = $2`,
[row.id, lockId]