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): emit cdp_cyclotron_v2_db_write_failure metric on real db failures (#60447)

Daniel Marchuk9e565eca1561
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 5f8d1f7aae0c..4cdaaddf7bd0 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -1,9 +1,25 @@
import { Pool } from 'pg'
+import { Counter } from 'prom-client'
import { v7 as uuidv7 } from 'uuid'
+import { isTransientPgError } from '../../../utils/db/postgres'
import { logger } from '../../../utils/logger'
import { CyclotronV2JobInit, CyclotronV2JobInitSchema, CyclotronV2ManagerConfig } from './types'
+// Counts Postgres write failures from createJob / bulkCreateJobs *after* input
+// validation has passed. Zod parse errors and the overwrite-conflict logical
+// error do not increment this counter. The `kind` label splits failures into:
+// - "logical": schema drift, constraint violation, anything that won't fix
+// itself. Any non-zero rate is page-worthy.
+// - "transient": PG / pgbouncer connection issues (matched against
+// POSTGRES_UNAVAILABLE_ERROR_MESSAGES). Brief blips are noise; sustained
+// rate indicates the database is unhealthy.
+const dbWriteFailureCounter = new Counter({
+ name: 'cdp_cyclotron_v2_db_write_failure',
+ help: 'Failed Postgres writes to cyclotron_jobs (input already validated), split by kind=logical|transient.',
+ labelNames: ['kind'] as const,
+})
+
/**
* Thrown when an `overwriteExisting` createJob / bulkCreateJobs hits a row
* that's still in an active state ('available' or 'running'). Callers should
@@ -75,30 +91,36 @@ export class CyclotronV2Manager {
WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')
RETURNING id`
: 'RETURNING id'
- const result = await this.pool.query<{ id: string }>(
- `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)
- VALUES ($1, $2, $3, $4, 'available', $5, $6, $7,
- NULL, NULL, 0, 0, $7,
- $8, $9, $10, $11, $12)
- ${upsertClause}`,
- [
- id,
- job.teamId,
- job.functionId ?? null,
- job.queueName,
- job.priority ?? 0,
- job.scheduled ?? now,
- now,
- job.parentRunId ?? null,
- job.state ?? null,
- job.distinctId ?? null,
- job.personId ?? null,
- job.actionId ?? null,
- ]
- )
+ let result: { rows: { id: string }[] }
+ try {
+ result = await this.pool.query<{ id: string }>(
+ `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)
+ VALUES ($1, $2, $3, $4, 'available', $5, $6, $7,
+ NULL, NULL, 0, 0, $7,
+ $8, $9, $10, $11, $12)
+ ${upsertClause}`,
+ [
+ id,
+ job.teamId,
+ job.functionId ?? null,
+ job.queueName,
+ job.priority ?? 0,
+ job.scheduled ?? now,
+ now,
+ job.parentRunId ?? null,
+ job.state ?? null,
+ job.distinctId ?? null,
+ job.personId ?? null,
+ job.actionId ?? null,
+ ]
+ )
+ } catch (err) {
+ dbWriteFailureCounter.labels({ kind: isTransientPgError(err) ? 'transient' : 'logical' }).inc()
+ throw err
+ }
if (job.overwriteExisting && result.rows.length === 0) {
// Existing row was in an active state — refuse to clobber.
throw new CyclotronJobConflictError(id)
@@ -171,46 +193,52 @@ export class CyclotronV2Manager {
WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')
RETURNING id`
: 'RETURNING id'
- const result = await this.pool.query<{ id: string }>(
- `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[])
- ${upsertClause}`,
- [
- ids,
- teamIds,
- functionIds,
- queueNames,
- priorities,
- scheduleds,
- parentRunIds,
- states,
- distinctIds,
- personIds,
- actionIds,
- now,
- ]
- )
+ let result: { rows: { id: string }[] }
+ try {
+ result = await this.pool.query<{ id: string }>(
+ `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[])
+ ${upsertClause}`,
+ [
+ ids,
+ teamIds,
+ functionIds,
+ queueNames,
+ priorities,
+ scheduleds,
+ parentRunIds,
+ states,
+ distinctIds,
+ personIds,
+ actionIds,
+ now,
+ ]
+ )
+ } catch (err) {
+ dbWriteFailureCounter.labels({ kind: isTransientPgError(err) ? 'transient' : 'logical' }).inc()
+ throw err
+ }
if (overwriteExisting) {
const returnedIds = new Set(result.rows.map((r) => r.id))
diff --git a/nodejs/src/utils/db/postgres.ts b/nodejs/src/utils/db/postgres.ts
index 48fd262e0e30..decdffa2c9f9 100644
--- a/nodejs/src/utils/db/postgres.ts
+++ b/nodejs/src/utils/db/postgres.ts
@@ -56,6 +56,11 @@ const POSTGRES_UNAVAILABLE_ERROR_MESSAGES = [
'server login has been failing', // PgBouncer cannot authenticate with upstream PG
]
+export function isTransientPgError(err: unknown): boolean {
+ const message = (err as Error | undefined)?.message
+ return !!message && POSTGRES_UNAVAILABLE_ERROR_MESSAGES.some((m) => message.includes(m))
+}
+
export enum PostgresUse {
COMMON_READ, // Read replica on the common tables, uses need to account for possible replication delay
COMMON_WRITE, // Main PG master with common tables, we need to move as many queries away from it as possible
diff --git a/nodejs/tests/utils/db/postgres.test.ts b/nodejs/tests/utils/db/postgres.test.ts
index 434bfc07ebd6..b70fb5f330d8 100644
--- a/nodejs/tests/utils/db/postgres.test.ts
+++ b/nodejs/tests/utils/db/postgres.test.ts
@@ -1,5 +1,39 @@
import { DependencyUnavailableError } from '../../../src/utils/db/error'
-import { PostgresUse, handlePostgresError } from '../../../src/utils/db/postgres'
+import { PostgresUse, handlePostgresError, isTransientPgError } from '../../../src/utils/db/postgres'
+
+describe('isTransientPgError', () => {
+ it.each([
+ ['connection to server at "pg:5432" refused'],
+ ['could not translate host name "pg" to address'],
+ ['server conn crashed'],
+ ['no more connections allowed (max_client_conn)'],
+ ['server closed the connection unexpectedly'],
+ ['getaddrinfo EAI_AGAIN pg'],
+ ['Connection terminated unexpectedly'],
+ ['connect ECONNREFUSED 127.0.0.1:5432'],
+ ['connect ETIMEDOUT 10.0.0.1:5432'],
+ ['query_wait_timeout'],
+ ['server login has been failing, try again later (server_login_retry)'],
+ ])('returns true for transient error "%s"', (message) => {
+ expect(isTransientPgError(new Error(message))).toBe(true)
+ })
+
+ it.each([
+ ['duplicate key value violates unique constraint'],
+ ['relation "table" does not exist'],
+ ['column "foo" of relation "cyclotron_jobs" does not exist'],
+ ['syntax error at or near "SELECT"'],
+ [''],
+ ])('returns false for non-transient error "%s"', (message) => {
+ expect(isTransientPgError(new Error(message))).toBe(false)
+ })
+
+ it('returns false when input is not an Error', () => {
+ expect(isTransientPgError(undefined)).toBe(false)
+ expect(isTransientPgError(null)).toBe(false)
+ expect(isTransientPgError('ECONNREFUSED')).toBe(false)
+ })
+})
describe('handlePostgresError', () => {
it.each([