: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): record cyclotron-v2 poison pills before deleting them (#64156)
Daniel Marchuk33e8fbc163bd
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 0e2bd33bc3c7..b5639e7cf1be 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -145,6 +145,11 @@ export type CdpConfig = ClickhouseConfig & {CYCLOTRON_NODE_JANITOR_STALL_TIMEOUT_MS: numberCYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT: numberCYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS: number+ // Kill-switch for poison-pill recovery. When false the janitor reverts to+ // master's pre-recovery behavior — mark poison pills failed with no replay+ // record (a give-up is lost, exactly as before this change). Flip to false to+ // roll back the recovery machinery instantly without a redeploy. Default true.+ CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: boolean}export function getDefaultCdpConfig(): CdpConfig {@@ -282,5 +287,6 @@ export function getDefaultCdpConfig(): CdpConfig {CYCLOTRON_NODE_JANITOR_STALL_TIMEOUT_MS: 30000,CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT: 3,CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS: 10000,+ CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: true,}}diff --git a/nodejs/src/cdp/services/cyclotron-v2/README.md b/nodejs/src/cdp/services/cyclotron-v2/README.mdindex 3ef183a4f379..f972ab4571f2 100644--- a/nodejs/src/cdp/services/cyclotron-v2/README.md+++ b/nodejs/src/cdp/services/cyclotron-v2/README.md@@ -38,7 +38,13 @@ Responsibilities:- **Cleanup** — bounded `DELETE` of terminal jobs older than a grace period- **Stalled job recovery** — reset jobs with stale heartbeats back to `available`-- **Poison pill detection** — fail jobs that have been reset too many times (`janitor_touch_count`)+- **Poison pill recovery** — give up on jobs that have been reset too many times+ (`janitor_touch_count`), but never silently: each is recorded as a `failed`,+ replayable invocation result on `hog_invocation_results` (discoverable in the+ Invocations UI, re-runnable by the rerun tooling) _before_ the cyclotron row is+ deleted. Workers reset `janitor_touch_count = 0` on every deliberate release, so+ the budget counts CONSECUTIVE stalls — long-lived waits don't accrue touches for+ life.- **Queue depth metrics** — Prometheus gauges per queue## Integration@@ -52,8 +58,13 @@ It's enabled via `CDP_CYCLOTRON_NODE_ENABLED=true` and routed alongside the exisFailed jobs are deleted by the janitor along with completed and canceled jobs.There is no dead-letter queue — a DLQ would fill the database exponentially-since failed jobs often produce more failed jobs on retry.-Errors are captured via logs and metrics before the job reaches terminal status.+since failed jobs often produce more failed jobs on retry, and it would be a+second recovery path operators have to learn alongside rerun.+Errors are captured via logs and metrics before the job reaches terminal status,+and poison-pill give-ups converge on the existing rerun system: they are written+as `failed` rows on `hog_invocation_results` (the table rerun already reads) and+deleted only once that row is durably enqueued, so a lost invocation is always+recoverable via the standard rerun tooling rather than a bespoke table.## Future workdiff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex 17d9f0086046..d6e5ddec78d9 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -1,7 +1,10 @@import { Pool } from 'pg'import { v7 as uuidv7 } from 'uuid'-import { CyclotronV2Janitor } from './janitor'+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 { CyclotronV2Worker } from './worker'@@ -34,14 +37,42 @@ function createWorker(queueName = QUEUE, overrides?: Record<string, unknown>): C})}-function createJanitor(overrides?: Record<string, unknown>): CyclotronV2Janitor {- return new CyclotronV2Janitor({- pool: { dbUrl: DB_URL },- cleanupGraceMs: 0,- stallTimeoutMs: 0,- maxTouchCount: 2,- ...overrides,- })+function createMockResults(ok = true): {+ service: HogInvocationResultsService+ recordTerminalFailureDurably: jest.Mock+} {+ const recordTerminalFailureDurably = jest.fn().mockResolvedValue(ok)+ return {+ service: { recordTerminalFailureDurably } as unknown as HogInvocationResultsService,+ recordTerminalFailureDurably,+ }+}++// A real HogInvocationResultsService over a fake producer — exercises the actual+// give-up row build (buildLifecycleRow + serialization), which the mock skips.+// This is the Postgres-rung guard for the invalid-date RangeError class.+function createRealResults(): { service: HogInvocationResultsService; produce: jest.Mock } {+ const produce = jest.fn().mockResolvedValue(undefined)+ const service = new HogInvocationResultsService({ produce } as any, { HOG_INVOCATION_RESULTS_ENABLED: true })+ return { service, produce }+}++function parseProducedResult(produce: jest.Mock): Record<string, any> {+ const value = produce.mock.calls[0][1].value as Buffer+ return parseJSON(value.toString('utf-8'))+}++function createJanitor(overrides?: Record<string, unknown>, results?: HogInvocationResultsService): CyclotronV2Janitor {+ return new CyclotronV2Janitor(+ {+ pool: { dbUrl: DB_URL },+ cleanupGraceMs: 0,+ stallTimeoutMs: 0,+ maxTouchCount: 2,+ ...overrides,+ },+ results+ )}interface RawJobRow {@@ -578,6 +609,26 @@ describe('Cyclotron V2', () => {expect((await queryJob(parentId)).status).toBe('completed')})+ it.each(['ack', 'fail', 'reschedule'] as const)(+ 'checks self in via %s and zeros janitor_touch_count (consecutive-stall counting)',+ async (kind) => {+ const { id: parentId, job } = await seedAndDequeue()+ // Simulate prior stalls the janitor had counted.+ await assertPool.query('UPDATE cyclotron_jobs SET janitor_touch_count = 2 WHERE id = $1', [+ parentId,+ ])++ await job.bulkCreateAndCheckIn({+ newJobs: [],+ selfDisposition:+ kind === 'reschedule' ? { kind: 'reschedule', scheduledAt: new Date() } : { kind },+ })++ // A deliberate self-checkin is a healthy release — the count resets.+ expect((await queryJob(parentId)).janitor_touch_count).toBe(0)+ }+ )+it('rolls back both writes if the insert fails (atomicity)', async () => {const { id: parentId, job } = await seedAndDequeue()@@ -838,6 +889,28 @@ describe('Cyclotron V2', () => {expect(row.last_heartbeat).toBeNull()})+ it.each(['ack', 'fail', 'cancel'] as const)(+ '%s() resets janitor_touch_count to 0 on a deliberate release',+ async (method) => {+ const { id, job } = await seedAndDequeue()+ // Simulate prior stalls the janitor had counted.+ await assertPool.query('UPDATE cyclotron_jobs SET janitor_touch_count = 2 WHERE id = $1', [id])++ await job[method]()++ expect((await queryJob(id)).janitor_touch_count).toBe(0)+ }+ )++ it('reschedule() resets janitor_touch_count to 0 so the poison budget counts consecutive stalls', async () => {+ const { id, job } = await seedAndDequeue()+ await assertPool.query('UPDATE cyclotron_jobs SET janitor_touch_count = 2 WHERE id = $1', [id])++ await job.reschedule()++ expect((await queryJob(id)).janitor_touch_count).toBe(0)+ })+it('reschedule() returns job to available', async () => {const { id, job } = await seedAndDequeue()await job.reschedule()@@ -1518,7 +1591,59 @@ describe('Cyclotron V2', () => {expect(row.janitor_touch_count).toBe(1)})- it('failPoisonPills fails jobs exceeding maxTouchCount', async () => {+ it('records a poison pill as a failed result and deletes it once recorded', async () => {+ const staleHeartbeat = new Date(Date.now() - 60_000)+ const jobId = uuidv7()+ await insertRawJob({+ id: jobId,+ function_id: uuidv7(),+ status: 'running',+ lock_id: uuidv7(),+ last_heartbeat: staleHeartbeat,+ janitor_touch_count: 3,+ })++ const { service, recordTerminalFailureDurably } = createMockResults(true)+ const janitor = createJanitor({ stallTimeoutMs: 1_000, maxTouchCount: 2 }, service)+ const result = await janitor.runOnce()+ await janitor.stop()++ expect(result.poisoned).toBe(1)+ expect(result.poisonedIds).toEqual([jobId])+ // Recorded as a failed, replayable invocation result first...+ expect(recordTerminalFailureDurably).toHaveBeenCalledTimes(1)+ expect(recordTerminalFailureDurably).toHaveBeenCalledWith(+ expect.objectContaining({ id: jobId }),+ expect.objectContaining({ errorKind: JANITOR_POISON_PILL_ERROR_KIND })+ )+ // ...then the cyclotron row is gone (no silent delete, no leftover).+ expect(await totalJobCount()).toBe(0)+ })++ it('keeps a poison pill (does not delete) when the recovery record cannot be produced', async () => {+ const staleHeartbeat = new Date(Date.now() - 60_000)+ const jobId = uuidv7()+ await insertRawJob({+ id: jobId,+ status: 'running',+ lock_id: uuidv7(),+ last_heartbeat: staleHeartbeat,+ janitor_touch_count: 3,+ })++ // produce fails → never delete, so the job is never silently dropped.+ const { service } = createMockResults(false)+ const janitor = createJanitor({ stallTimeoutMs: 1_000, maxTouchCount: 2 }, service)+ const result = await janitor.runOnce()+ await janitor.stop()++ expect(result.poisoned).toBe(0)+ expect(await totalJobCount()).toBe(1)+ // It is still reset to available so a recovered worker retries it.+ expect((await queryJob(jobId)).status).toBe('available')+ })++ it('keeps poison pills (never deletes) when no results service is wired', async () => {const staleHeartbeat = new Date(Date.now() - 60_000)const jobId = uuidv7()await insertRawJob({@@ -1533,18 +1658,43 @@ describe('Cyclotron V2', () => {const result = await janitor.runOnce()await janitor.stop()+ expect(result.poisoned).toBe(0)+ expect(await totalJobCount()).toBe(1)+ })++ it('marks poison pills failed (legacy behavior, no record) when recovery is disabled (kill-switch)', async () => {+ const staleHeartbeat = new Date(Date.now() - 60_000)+ const jobId = uuidv7()+ await insertRawJob({+ id: jobId,+ status: 'running',+ lock_id: uuidv7(),+ last_heartbeat: staleHeartbeat,+ janitor_touch_count: 3,+ })++ // A results service is wired, but the kill-switch reverts to master's+ // pre-recovery path: mark the pill failed, never record a replay row.+ const { service, recordTerminalFailureDurably } = createMockResults(true)+ const janitor = createJanitor(+ { stallTimeoutMs: 1_000, maxTouchCount: 2, poisonRecoveryEnabled: false },+ service+ )+ const result = await janitor.runOnce()+ await janitor.stop()+expect(result.poisoned).toBe(1)- const row = await queryJob(jobId)- expect(row.status).toBe('failed')+ expect(recordTerminalFailureDurably).not.toHaveBeenCalled()+ expect((await queryJob(jobId)).status).toBe('failed')})- it('poison pills are failed before stalled jobs are reset', async () => {+ it('gives up on poison pills before stalled jobs are reset', async () => {const staleHeartbeat = new Date(Date.now() - 60_000)- // This job has been touched enough times to be a poison pillconst poisonId = uuidv7()await insertRawJob({id: poisonId,+ function_id: uuidv7(),status: 'running',lock_id: uuidv7(),last_heartbeat: staleHeartbeat,@@ -1561,20 +1711,71 @@ describe('Cyclotron V2', () => {janitor_touch_count: 0,})- const janitor = createJanitor({ stallTimeoutMs: 1_000, maxTouchCount: 2 })+ const { service } = createMockResults(true)+ const janitor = createJanitor({ stallTimeoutMs: 1_000, maxTouchCount: 2 }, service)const result = await janitor.runOnce()await janitor.stop()expect(result.poisoned).toBe(1)expect(result.stalled).toBe(1)- const poison = await queryJob(poisonId)- expect(poison.status).toBe('failed')-+ // Poison pill recorded + deleted; the merely-stalled job survives, reset.+ await expect(queryJob(poisonId)).rejects.toThrow()const stalled = await queryJob(stalledId)expect(stalled.status).toBe('available')})+ it.each(['hogflow', 'email'])(+ 'builds and produces a valid failed hog_flow result for a poisoned %s-queue job',+ async (queueName) => {+ // Realistic parked-mid-flow state; the scheduled/created columns come+ // back from pg as ISO strings — the give-up row build must parse them+ // without throwing (the RangeError this guards against).+ const id = uuidv7()+ const functionId = uuidv7()+ const state = Buffer.from(+ JSON.stringify({+ state: {+ event: { uuid: uuidv7(), distinct_id: 'd1' },+ actionStepCount: 1,+ variables: { foo: 'bar' },+ currentAction: { id: 'wait_1', startedAtTimestamp: 1 },+ },+ })+ )+ await insertRawJob({+ id,+ function_id: functionId,+ queue_name: queueName,+ status: 'running',+ lock_id: uuidv7(),+ last_heartbeat: new Date(Date.now() - 60_000),+ janitor_touch_count: 5,+ state,+ })++ const { service, produce } = createRealResults()+ const janitor = createJanitor({ stallTimeoutMs: 1_000, maxTouchCount: 2 }, service)+ const result = await janitor.runOnce()+ await janitor.stop()++ expect(result.poisonedIds).toEqual([id])+ // The row was actually built + produced — where the invalid-date+ // RangeError used to throw and leave the job undeleted.+ expect(produce).toHaveBeenCalledTimes(1)+ const row = parseProducedResult(produce)+ expect(row.status).toBe('failed')+ expect(row.function_kind).toBe('hog_flow')+ expect(row.function_id).toBe(functionId)+ expect(row.error_kind).toBe(JANITOR_POISON_PILL_ERROR_KIND)+ // Timestamps must be real ISO microsecond strings, never NaN/"Invalid".+ expect(row.scheduled_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)+ expect(row.finished_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)+ // Recorded first, then deleted.+ await expect(queryJob(id)).rejects.toThrow()+ }+ )+it('measureQueueDepths returns correct counts per queue', async () => {await insertRawJob({ id: uuidv7(), queue_name: 'queue-a', status: 'available' })await insertRawJob({ id: uuidv7(), queue_name: 'queue-a', status: 'available' })diff --git a/nodejs/src/cdp/services/cyclotron-v2/index.ts b/nodejs/src/cdp/services/cyclotron-v2/index.tsindex 8f785d3a7230..de2c7748b003 100644--- a/nodejs/src/cdp/services/cyclotron-v2/index.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/index.ts@@ -1,7 +1,7 @@export { CyclotronV2Manager, CyclotronJobConflictError } from './manager'export { CyclotronV2Worker } from './worker'export { CyclotronV2RateLimitedWorker } from './worker-rate-limited'-export { CyclotronV2Janitor } from './janitor'+export { CyclotronV2Janitor, JANITOR_POISON_PILL_ERROR_KIND } from './janitor'export { CyclotronV2JanitorService } from './janitor-service'export type {CyclotronV2JobStatus,diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor-service.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor-service.tsindex cd5b89751002..abe767cb6734 100644--- a/nodejs/src/cdp/services/cyclotron-v2/janitor-service.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor-service.ts@@ -1,12 +1,13 @@import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService } from '../../../types'+import { HogInvocationResultsService } from '../monitoring/hog-invocation-results.service'import { CyclotronV2Janitor } from './janitor'import { CyclotronV2JanitorConfig } from './types'export class CyclotronV2JanitorService {private janitor: CyclotronV2Janitor- constructor(config: CyclotronV2JanitorConfig) {- this.janitor = new CyclotronV2Janitor(config)+ constructor(config: CyclotronV2JanitorConfig, invocationResults?: HogInvocationResultsService) {+ this.janitor = new CyclotronV2Janitor(config, invocationResults)}async start(): Promise<void> {diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.tsindex cfac48c40023..e1937218923d 100644--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts@@ -1,9 +1,18 @@+import { DateTime } from 'luxon'import { Pool } from 'pg'import { Counter, Gauge } from 'prom-client'import { logger } from '~/common/utils/logger'-import { CyclotronV2CleanupResult, CyclotronV2JanitorConfig } from './types'+import { 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'++// 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+// exactly these give-ups from the rerun tooling (rerun filter `error_kind`).+export const JANITOR_POISON_PILL_ERROR_KIND = 'janitor_poison_pill'const janitorDeletedCounter = new Counter({name: 'cdp_cyclotron_v2_janitor_deleted',@@ -18,7 +27,12 @@ const janitorStalledCounter = new Counter({const janitorPoisonedCounter = new Counter({name: 'cdp_cyclotron_v2_janitor_poisoned',- help: 'Number of poison pill jobs failed by the janitor',+ help: 'Number of poison pill jobs given up on (recorded as failed, replayable) by the janitor',+})++const janitorGiveUpSkippedCounter = new Counter({+ name: 'cdp_cyclotron_v2_janitor_give_up_skipped',+ help: 'Poison pills the janitor could not record a recovery row for, so kept (not deleted)',})const janitorRunCounter = new Counter({@@ -32,6 +46,25 @@ const queueDepthGauge = new Gauge({labelNames: ['queue'],})+interface PoisonRow {+ id: string+ team_id: number+ function_id: string | null+ queue_name: string+ priority: number+ // pg returns these as ISO strings here (same as the worker's dequeue rows),+ // not Date objects — parse with fromISO, never fromJSDate.+ scheduled: string+ created: string+ parent_run_id: string | null+ state: Buffer | null+ distinct_id: string | null+ person_id: string | null+ action_id: string | null+ janitor_touch_count: number+ transition_count: number+}+export class CyclotronV2Janitor {private pool: Poolprivate intervalHandle: ReturnType<typeof setInterval> | null = null@@ -41,8 +74,16 @@ export class CyclotronV2Janitor {private readonly stallTimeoutMs: numberprivate readonly maxTouchCount: numberprivate readonly cleanupGraceMs: number-- constructor(config: CyclotronV2JanitorConfig) {+ private readonly poisonRecoveryEnabled: boolean++ constructor(+ config: CyclotronV2JanitorConfig,+ // Optional so the v1 postgres paths and unit tests that don't exercise+ // the give-up path can construct a janitor without Kafka. When absent+ // the janitor never deletes poison pills (it only resets/retries) — it+ // refuses to drop a job it can't record a recovery row for.+ private invocationResults?: HogInvocationResultsService+ ) {this.pool = new Pool({connectionString: config.pool.dbUrl,max: config.pool.maxConnections ?? 5,@@ -53,6 +94,13 @@ export class CyclotronV2Janitor {this.stallTimeoutMs = config.stallTimeoutMs ?? 30000this.maxTouchCount = config.maxTouchCount ?? 3this.cleanupGraceMs = config.cleanupGraceMs ?? 10000+ this.poisonRecoveryEnabled = config.poisonRecoveryEnabled ?? true++ if (!this.poisonRecoveryEnabled) {+ logger.warn(+ 'CyclotronV2Janitor poison-pill recovery DISABLED via CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED=false — reverting to legacy behavior: poison pills are marked failed with no replay record'+ )+ }}async start(): Promise<void> {@@ -70,17 +118,27 @@ export class CyclotronV2Janitor {}async runOnce(): Promise<CyclotronV2CleanupResult> {- const deleted = await this.cleanupTerminalJobs()- const poisoned = await this.failPoisonPills()+ const deletedCounts = await this.cleanupTerminalJobs()+ const deleted = Object.values(deletedCounts).reduce((a, b) => a + b, 0)++ // Give up on genuine poison pills. The kill-switch picks between two+ // self-contained paths with no inline flag checks beyond this branch:+ // the new record-then-delete path, or master's legacy mark-failed path.+ // The legacy path (and the flag) can be deleted wholesale once we trust+ // recording in production.+ const poisonedIds = this.poisonRecoveryEnabled+ ? await this.recordAndDeletePoisonPills()+ : await this.failPoisonPills()+const stalled = await this.resetStalledJobs()const depths = await this.measureQueueDepths()janitorRunCounter.inc()- return { deleted, stalled, poisoned, depths }+ return { deleted, stalled, poisoned: poisonedIds.length, poisonedIds, depths }}- private async cleanupTerminalJobs(): Promise<number> {+ private async cleanupTerminalJobs(): Promise<Record<string, number>> {const cutoff = new Date(Date.now() - this.cleanupGraceMs)const result = await this.pool.query<{ status: string; count: string }>(@@ -115,14 +173,21 @@ export class CyclotronV2Janitor {logger.info('CyclotronV2Janitor cleaned up terminal jobs', { counts, total })}- return total+ return counts}- private async failPoisonPills(): Promise<number> {- // Poison pills: running jobs with stale heartbeats that have been reset too many times+ /**+ * Kill-switch OFF path — restores master's pre-recovery behavior verbatim:+ * mark poison pills `failed` (then `cleanupTerminalJobs` sweeps them like any+ * other failed job) with no recovery record. A give-up here is lost to replay,+ * exactly as before this change — that is what OFF means. Kept as a+ * self-contained counterpart to `recordAndDeletePoisonPills` so this whole+ * path, and the flag, can be deleted once recording is trusted in production.+ */+ private async failPoisonPills(): Promise<string[]> {const heartbeatCutoff = new Date(Date.now() - this.stallTimeoutMs)- const result = await this.pool.query(+ const result = await this.pool.query<{ id: string }>(`UPDATE cyclotron_jobsSET status = 'failed', lock_id = NULL, last_heartbeat = NULL,last_transition = NOW(), transition_count = transition_count + 1@@ -133,17 +198,142 @@ export class CyclotronV2Janitor {AND COALESCE(last_heartbeat, $1) <= $1AND janitor_touch_count >= $2FOR UPDATE SKIP LOCKED- )`,+ )+ RETURNING id`,[heartbeatCutoff, this.maxTouchCount])- const count = result.rowCount ?? 0- if (count > 0) {- janitorPoisonedCounter.inc(count)- logger.warn('CyclotronV2Janitor failed poison pill jobs', { count })+ const ids = result.rows.map((r) => r.id)+ if (ids.length > 0) {+ janitorPoisonedCounter.inc(ids.length)+ logger.warn('CyclotronV2Janitor failed poison pill jobs (recovery disabled, no replay record)', {+ count: ids.length,+ })}+ return ids+ }- return count+ /**+ * Give up on poison pills: running jobs with a stale heartbeat that have+ * been reset too many times. Each one is recorded as a `failed`, replayable+ * invocation result (discoverable in the Invocations UI, re-runnable by the+ * existing rerun tooling) and only then deleted — so there is never a window+ * where the cyclotron row is gone but no recovery record exists. The+ * original incident deleted these with no trace; here every give-up is+ * logged with its id and recorded for replay.+ */+ private async recordAndDeletePoisonPills(): Promise<string[]> {+ const heartbeatCutoff = new Date(Date.now() - this.stallTimeoutMs)++ const result = await this.pool.query<PoisonRow>(+ `SELECT id, team_id, function_id, queue_name, priority, scheduled, created,+ parent_run_id, state, distinct_id, person_id, action_id,+ janitor_touch_count, transition_count+ FROM cyclotron_jobs+ WHERE status = 'running'+ AND COALESCE(last_heartbeat, $1) <= $1+ AND janitor_touch_count >= $2+ ORDER BY last_transition ASC+ LIMIT $3+ FOR UPDATE SKIP LOCKED`,+ [heartbeatCutoff, this.maxTouchCount, this.cleanupBatchSize]+ )++ if (result.rows.length === 0) {+ return []+ }++ if (!this.invocationResults) {+ // No way to record a recovery row — keep the jobs rather than drop+ // them silently. resetStalledJobs will retry them this cycle.+ janitorGiveUpSkippedCounter.inc(result.rows.length)+ logger.warn('CyclotronV2Janitor cannot record poison pill recovery (no results service), keeping jobs', {+ count: result.rows.length,+ })+ return []+ }++ const recordedIds: string[] = []+ let skipped = 0+ for (const row of result.rows) {+ const invocation = this.poisonRowToInvocation(row)+ const ok = await this.invocationResults.recordTerminalFailureDurably(invocation, {+ error: `poison pill: stalled and reset ${row.janitor_touch_count} times without completing`,+ errorKind: JANITOR_POISON_PILL_ERROR_KIND,+ })+ if (ok) {+ recordedIds.push(row.id)+ } else {+ skipped+++ }+ }++ if (skipped > 0) {+ janitorGiveUpSkippedCounter.inc(skipped)+ logger.warn('CyclotronV2Janitor kept poison pills it could not durably record', { count: skipped })+ }++ if (recordedIds.length === 0) {+ return []+ }++ // Re-assert the FULL poison predicate (not just status='running') in the+ // DELETE. Between the SELECT and here a row could have been reset to+ // 'available' and re-dequeued by a worker — that re-dequeue stamps a+ // fresh heartbeat, so the stale-heartbeat / touch-count guard no longer+ // matches and we won't delete an actively-running job. RETURNING gives+ // the rows actually removed, so the metric/log reflect real give-ups+ // even if a concurrent janitor or worker raced us to some of them.+ const deleted = await this.pool.query<{ id: string }>(+ `DELETE FROM cyclotron_jobs+ WHERE id = ANY($1::uuid[])+ AND status = 'running'+ AND COALESCE(last_heartbeat, $2) <= $2+ AND janitor_touch_count >= $3+ RETURNING id`,+ [recordedIds, heartbeatCutoff, this.maxTouchCount]+ )+ const deletedIds = deleted.rows.map((r) => r.id)++ if (deletedIds.length > 0) {+ janitorPoisonedCounter.inc(deletedIds.length)+ logger.warn('CyclotronV2Janitor gave up on poison pill jobs (recorded as failed, replayable)', {+ count: deletedIds.length,+ ids: deletedIds,+ })+ }++ return deletedIds+ }++ // Turn a raw poisoned row into a hog flow invocation the results service can+ // serialize. postgres-v2 backs hog flows, so we tag it as such — the stub+ // `hogFlow` carries only the id the lifecycle row needs (function_id), while+ // the rerun path rebuilds the full flow from the function id on replay.+ private poisonRowToInvocation(row: PoisonRow): CyclotronJobInvocationHogFlow {+ const job: CyclotronV2DequeuedJob = {+ id: row.id,+ teamId: row.team_id,+ functionId: row.function_id,+ queueName: row.queue_name,+ priority: row.priority,+ scheduled: DateTime.fromISO(row.scheduled, { zone: 'utc' }),+ created: DateTime.fromISO(row.created, { zone: 'utc' }),+ parentRunId: row.parent_run_id,+ transitionCount: row.transition_count,+ state: row.state,+ distinctId: row.distinct_id,+ personId: row.person_id,+ actionId: row.action_id,+ ack: () => Promise.resolve(),+ fail: () => Promise.resolve(),+ reschedule: () => Promise.resolve(),+ cancel: () => Promise.resolve(),+ heartbeat: () => Promise.resolve(),+ bulkCreateAndCheckIn: () => Promise.resolve({ newJobIds: [] }),+ }+ const invocation = v2JobToInvocation(job)+ return { ...invocation, hogFlow: { id: invocation.functionId } } as CyclotronJobInvocationHogFlow}private async resetStalledJobs(): Promise<number> {diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.tsindex e95495bc7997..73b66b8f6f41 100644--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts@@ -129,11 +129,17 @@ export type CyclotronV2JanitorConfig = {stallTimeoutMs?: numbermaxTouchCount?: numbercleanupGraceMs?: number+ // Kill-switch. When false the janitor reverts to master's legacy path — mark+ // poison pills failed with no replay record (a give-up is lost). Defaults to true.+ poisonRecoveryEnabled?: boolean}export type CyclotronV2CleanupResult = {deleted: numberstalled: number+ // Jobs the janitor gave up on this cycle (recorded as failed, replayable+ // invocation results before deletion).poisoned: number+ poisonedIds: string[]depths: Map<string, number>}diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.tsindex 2f42c75c06ee..dff52877dc19 100644--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts@@ -140,11 +140,15 @@ async function updateSelfInTx(lockId: string,disposition: CyclotronV2BulkCreateAndCheckInInput['selfDisposition']): Promise<void> {+ // Deliberate self-checkins zero janitor_touch_count for the same reason the+ // wrapJob dispositions do — the poison budget counts CONSECUTIVE stalls, so a+ // healthy batch-resolve release must not leave a stale touch count behind.if (disposition.kind === 'ack') {const result = await client.query(`UPDATE cyclotron_jobsSET status = 'completed', lock_id = NULL, last_heartbeat = NULL,- last_transition = NOW(), transition_count = transition_count + 1+ last_transition = NOW(), transition_count = transition_count + 1,+ janitor_touch_count = 0WHERE id = $1 AND lock_id = $2`,[jobId, lockId])@@ -155,7 +159,8 @@ async function updateSelfInTx(const result = await client.query(`UPDATE cyclotron_jobsSET status = 'failed', lock_id = NULL, last_heartbeat = NULL,- last_transition = NOW(), transition_count = transition_count + 1+ last_transition = NOW(), transition_count = transition_count + 1,+ janitor_touch_count = 0WHERE id = $1 AND lock_id = $2`,[jobId, lockId])@@ -170,6 +175,7 @@ async function updateSelfInTx(`last_heartbeat = NULL`,`last_transition = NOW()`,`transition_count = transition_count + 1`,+ `janitor_touch_count = 0`,`scheduled = $3`,]const params: any[] = [jobId, lockId, scheduled]@@ -421,7 +427,8 @@ export class CyclotronV2Worker {await pool.query(`UPDATE cyclotron_jobsSET status = 'completed', lock_id = NULL, last_heartbeat = NULL,- last_transition = NOW(), transition_count = transition_count + 1+ last_transition = NOW(), transition_count = transition_count + 1,+ janitor_touch_count = 0WHERE id = $1 AND lock_id = $2`,[row.id, lockId])@@ -432,7 +439,8 @@ export class CyclotronV2Worker {await pool.query(`UPDATE cyclotron_jobsSET status = 'failed', lock_id = NULL, last_heartbeat = NULL,- last_transition = NOW(), transition_count = transition_count + 1+ last_transition = NOW(), transition_count = transition_count + 1,+ janitor_touch_count = 0WHERE id = $1 AND lock_id = $2`,[row.id, lockId])@@ -449,6 +457,11 @@ export class CyclotronV2Worker {`last_heartbeat = NULL`,`last_transition = NOW()`,`transition_count = transition_count + 1`,+ // 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+ // their whole life and get mistaken for poison pills.+ `janitor_touch_count = 0`,`scheduled = $3`,]const params: any[] = [row.id, lockId, scheduled]@@ -501,7 +514,8 @@ export class CyclotronV2Worker {await pool.query(`UPDATE cyclotron_jobsSET status = 'canceled', lock_id = NULL, last_heartbeat = NULL,- last_transition = NOW(), transition_count = transition_count + 1+ last_transition = NOW(), transition_count = transition_count + 1,+ janitor_touch_count = 0WHERE id = $1 AND lock_id = $2`,[row.id, lockId])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 d72ecf6fdc52..c7071f88a0da 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@@ -340,7 +340,7 @@ export function extractActionId(invocation: CyclotronJobInvocation): string | nureturn (invocation as LookupColumnSource).state?.currentAction?.id || null}-function v2JobToInvocation(job: CyclotronV2DequeuedJob): CyclotronJobInvocation {+export function v2JobToInvocation(job: CyclotronV2DequeuedJob): CyclotronJobInvocation {let parsed: SerializedJobState = { state: null }if (job.state) {diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.tsindex 1dc1d4fce150..baa26582ec0b 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts@@ -57,6 +57,40 @@ describe('HogInvocationResultsService', () => {})})+ describe('recordTerminalFailureDurably', () => {+ it('produces a failed row with an overridden error_kind and reports success', async () => {+ const invocation = createExampleInvocation()+ const ok = await service.recordTerminalFailureDurably(invocation, {+ error: 'poison pill: stalled and reset 3 times without completing',+ errorKind: 'janitor_poison_pill',+ })++ expect(ok).toBe(true)+ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(1)+ expect(rows[0].status).toBe('failed')+ expect(rows[0].error_kind).toBe('janitor_poison_pill')+ expect(rows[0].error_message).toContain('poison pill')+ expect(rows[0].invocation_id).toBe(invocation.id)+ })++ it('returns false (does not throw) when the produce fails — caller must not delete', async () => {+ outputs.produce.mockRejectedValueOnce(new Error('broker unavailable'))+ const ok = await service.recordTerminalFailureDurably(createExampleInvocation(), {+ error: 'boom',+ errorKind: 'janitor_poison_pill',+ })+ expect(ok).toBe(false)+ })++ it('returns false when recording is disabled', async () => {+ service = new HogInvocationResultsService(outputs, { HOG_INVOCATION_RESULTS_ENABLED: false })+ const ok = await service.recordTerminalFailureDurably(createExampleInvocation(), { error: 'boom' })+ expect(ok).toBe(false)+ expect(outputs.produce).not.toHaveBeenCalled()+ })+ })+describe('queueLifecycleRow', () => {it('writes a status=running row with start timing and no error fields', async () => {const invocation = createExampleInvocation()diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.tsindex 664fe398ba63..f80557df1e39 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts@@ -325,6 +325,7 @@ export class HogInvocationResultsService {status: 'running' | 'succeeded' | 'failed',opts: {error?: unknown+ errorKind?: stringstartedAt?: DatefinishedAt?: Date} = {}@@ -333,9 +334,30 @@ export class HogInvocationResultsService {return}+ const row = this.buildLifecycleRow(invocation, status, opts)+ counterHogInvocationResultRowsProduced.labels(row.function_kind, row.status).inc()+ this.queuedRows.push(row)+ hogInvocationResultsPendingMessages.set(this.queuedRows.length)+ }++ private buildLifecycleRow(+ invocation: CyclotronJobInvocation,+ status: 'running' | 'succeeded' | 'failed',+ opts: {+ error?: unknown+ errorKind?: string+ startedAt?: Date+ finishedAt?: Date+ }+ ): HogInvocationResultRow {const now = new Date()const trigger = extractTriggerFields(invocation)- const { kind: errorKind, message: errorMessage } = classifyError(opts.error)+ const classified = classifyError(opts.error)+ // An explicit `errorKind` overrides the derived one so callers (e.g. the+ // janitor giving up on a poison pill) can stamp a stable, filterable+ // kind that the rerun tooling can target directly.+ const errorKind = opts.errorKind ?? classified.kind+ const errorMessage = classified.messageconst startedAt = opts.startedAt ?? (status === 'running' ? now : undefined)const finishedAt = opts.finishedAt ?? (status !== 'running' ? now : undefined)const durationMs =@@ -399,9 +421,61 @@ export class HogInvocationResultsService {is_deleted: 0,}- counterHogInvocationResultRowsProduced.labels(row.function_kind, row.status).inc()- this.queuedRows.push(row)- hogInvocationResultsPendingMessages.set(this.queuedRows.length)+ return row+ }++ /**+ * Produce a single terminal `failed` lifecycle row and await the broker+ * ack, returning `true` only once the row is durably enqueued. Bypasses the+ * batched queue/flush path so the caller can establish a strict ordering —+ * the janitor records a poison pill's give-up here BEFORE deleting the+ * cyclotron row, closing the window where the row could be gone with no+ * recovery record. Returns `false` (never throws) when recording is+ * disabled or the produce fails, so the caller can keep the job instead of+ * dropping it silently.+ */+ async recordTerminalFailureDurably(+ invocation: CyclotronJobInvocation,+ opts: { error?: unknown; errorKind?: string } = {}+ ): Promise<boolean> {+ if (!this.config.HOG_INVOCATION_RESULTS_ENABLED) {+ return false+ }++ // Build inside the try too — a malformed invocation (e.g. an unparseable+ // date) must fail this record safely so the caller keeps the job, never+ // crash the whole janitor cycle.+ try {+ const row = this.buildLifecycleRow(invocation, 'failed', opts)+ await this.produceRow(row)+ counterHogInvocationResultRowsProduced.labels(row.function_kind, row.status).inc()+ return true+ } catch (error) {+ counterHogInvocationResultProduceFailed.inc()+ logger.error('⚠️', `failed to durably record terminal failure: ${error}`, {+ error: String(error),+ invocation_id: invocation.id,+ })+ captureException(error)+ return false+ }+ }++ private async produceRow(row: HogInvocationResultRow): Promise<void> {+ const value = Buffer.from(+ safeClickhouseString(+ JSON.stringify({+ ...row,+ invocation_globals: await compressInvocationGlobals(row.invocation_globals),+ })+ )+ )+ await this.outputs.produce(HOG_INVOCATION_RESULTS_OUTPUT, {+ // Partition by invocation_id so all rows for a single invocation+ // land on the same Kafka partition (and the same ClickHouse shard).+ key: Buffer.from(row.invocation_id),+ value,+ })}/**@@ -515,36 +589,18 @@ export class HogInvocationResultsService {hogInvocationResultsPendingMessages.set(0)await Promise.all(- rows.map(async (row) => {- const value = Buffer.from(- safeClickhouseString(- JSON.stringify({- ...row,- invocation_globals: await compressInvocationGlobals(row.invocation_globals),- })- )- )- return this.outputs- .produce(HOG_INVOCATION_RESULTS_OUTPUT, {- // Partition by invocation_id so all rows for a single- // invocation land on the same Kafka partition (and- // therefore the same ClickHouse shard via- // cityHash64(invocation_id) — keeping the- // ReplacingMergeTree merge local).- key: Buffer.from(row.invocation_id),- value,- })- .catch((error) => {- counterHogInvocationResultProduceFailed.inc()- // Best-effort — never disrupt invocation processing- // for a monitoring write.- logger.error('⚠️', `failed to produce hog invocation result: ${error}`, {- error: String(error),- invocation_id: row.invocation_id,- })- captureException(error)+ rows.map((row) =>+ this.produceRow(row).catch((error) => {+ counterHogInvocationResultProduceFailed.inc()+ // Best-effort — never disrupt invocation processing for a+ // monitoring write.+ logger.error('⚠️', `failed to produce hog invocation result: ${error}`, {+ error: String(error),+ invocation_id: row.invocation_id,})- })+ captureException(error)+ })+ ))}}diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 3396ce3198ea..8efb14da3b7b 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -23,7 +23,12 @@ import express from 'ultimate-express'import { HogFlow } from '~/cdp/schema/hogflow'import { setupExpressApp } from '~/common/api/router'-import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES, KAFKA_MESSAGE_ASSETS } from '~/common/config/kafka-topics'+import {+ KAFKA_APP_METRICS_2,+ KAFKA_HOG_INVOCATION_RESULTS,+ KAFKA_LOG_ENTRIES,+ KAFKA_MESSAGE_ASSETS,+} from '~/common/config/kafka-topics'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { InternalPersonWithDistinctId, PersonReadRepository } from '~/common/persons/repositories/person-repository'import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'@@ -50,7 +55,13 @@ 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 { CyclotronV2Janitor, CyclotronV2Manager, CyclotronV2Worker } from './services/cyclotron-v2'+import { createCdpOutputsRegistry } from './outputs/registry'+import {+ CyclotronV2Janitor,+ CyclotronV2Manager,+ CyclotronV2Worker,+ JANITOR_POISON_PILL_ERROR_KIND,+} from './services/cyclotron-v2'import {HOGFLOW_BATCH_RESOLVE_QUEUE,MAX_RESOLVER_ATTEMPTS,@@ -62,6 +73,7 @@ import { CyclotronJobQueuePostgres } from './services/job-queue/job-queue-postgrimport { 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'+import { HogInvocationResultsService } from './services/monitoring/hog-invocation-results.service'import { RateLimiterService } from './services/rate-limiter/rate-limiter.service'import { HogFunctionInvocationGlobals } from './types'import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals } from './utils'@@ -4008,3 +4020,144 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {expect(children.rows).toHaveLength(0)})})++// Janitor poison-pill recovery (postgres-v2). Exercises the REAL results service+// + real Kafka produce — the seam the mocked unit tests can't cover: an isolated+// poison pill is recorded as a failed, replayable result on hog_invocation_results+// BEFORE its cyclotron row is deleted, and with recovery disabled the janitor+// reverts to master's legacy path (marks the pill failed, no recovery record).+describe('Workflows E2E (janitor poison-pill recovery, postgres-v2)', () => {+ jest.setTimeout(30000)++ let hub: Hub+ let kafkaProducer: KafkaProducerWrapper+ let mockProducerObserver: KafkaProducerObserver+ let team: Team+ let cyclotronPool: Pool+ let invocationResults: HogInvocationResultsService+ let janitor: CyclotronV2Janitor | undefined++ beforeAll(() => {+ cyclotronPool = new Pool({ connectionString: CYCLOTRON_NODE_DB_URL })+ })++ afterAll(async () => {+ await cyclotronPool.end()+ })++ beforeEach(async () => {+ MockKafkaProducerWrapper.create = jest.fn((...args) => ActualKafkaProducerWrapper.create(...args))++ // KAFKA_HOG_INVOCATION_RESULTS isn't in TEST_KAFKA_TOPICS — the janitor+ // produces the give-up record there, so it must exist or the produce+ // fails and the row is (correctly) never deleted.+ await ensureKafkaTopics([...TEST_KAFKA_TOPICS, KAFKA_HOG_INVOCATION_RESULTS])+ await resetTestDatabase()+ await cyclotronPool.query('DELETE FROM cyclotron_jobs')++ hub = await createHub()+ // The give-up record path is gated on this flag (off by default outside dev).+ hub.HOG_INVOCATION_RESULTS_ENABLED = true++ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ mockProducerObserver = new KafkaProducerObserver(kafkaProducer)+ team = await getFirstTeam(hub.postgres)+ mockProducerObserver.resetKafkaProducer()++ const deps = createCdpConsumerDeps(hub, kafkaProducer)+ const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, hub)+ invocationResults = new HogInvocationResultsService(outputs, hub)+ })++ afterEach(async () => {+ await janitor?.stop().catch(() => {})+ janitor = undefined+ await kafkaProducer.disconnect()+ await closeHub(hub)+ mockProducerObserver.resetKafkaProducer()+ })++ function createJanitor(overrides: Record<string, unknown> = {}): CyclotronV2Janitor {+ return new CyclotronV2Janitor(+ {+ pool: { dbUrl: CYCLOTRON_NODE_DB_URL },+ cleanupGraceMs: 0,+ stallTimeoutMs: 1000,+ maxTouchCount: 3,+ ...overrides,+ },+ invocationResults+ )+ }++ // A hogflow job stuck 'running' with a long-stale heartbeat and a touch count+ // over the budget. The serialized state mirrors a wait_until_condition that+ // had already advanced past earlier actions.+ async function insertPoisonedHogflowJob(): Promise<string> {+ const id = new UUIDT().toString()+ const state = Buffer.from(+ JSON.stringify({+ state: {+ event: { uuid: 'evt-poison', distinct_id: 'd-poison' },+ actionStepCount: 2,+ variables: {},+ currentAction: { id: 'wait_condition', startedAtTimestamp: 1 },+ },+ })+ )+ await cyclotronPool.query(+ `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, state)+ VALUES ($1, $2, $3, 'hogflow', 'running'::CyclotronJobStatus, 0, NOW(), NOW(),+ $4, NOW() - INTERVAL '5 minutes', 5, 10, NOW(), $5)`,+ [id, team.id, new UUIDT().toString(), new UUIDT().toString(), state]+ )+ return id+ }++ it('records an isolated poison pill as a failed, replayable result and only then deletes it', async () => {+ const id = await insertPoisonedHogflowJob()++ janitor = createJanitor()+ const result = await janitor.runOnce()++ expect(result.poisonedIds).toEqual([id])++ // A failed lifecycle row reached the hog_invocation_results topic so the+ // run is discoverable in the Invocations UI and replayable by rerun.+ await waitForExpect(() => {+ const rows = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)+ expect(rows.some((m: any) => m.value.invocation_id === id)).toBe(true)+ }, 10000)++ const row = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)+ .find((m: any) => m.value.invocation_id === id)!.value+ expect(row.status).toBe('failed')+ expect(row.function_kind).toBe('hog_flow')+ expect(row.function_id).toBeTruthy()+ expect(row.error_kind).toBe(JANITOR_POISON_PILL_ERROR_KIND)++ // The cyclotron row is gone — but only because the record exists first.+ const remaining = await cyclotronPool.query('SELECT 1 FROM cyclotron_jobs WHERE id = $1', [id])+ expect(remaining.rowCount).toBe(0)+ })++ it('reverts to legacy mark-failed (records nothing) when recovery is disabled', async () => {+ const id = await insertPoisonedHogflowJob()++ janitor = createJanitor({ poisonRecoveryEnabled: false })+ const result = await janitor.runOnce()++ // Kill-switch off → master's legacy path: mark the pill failed and produce+ // no recovery record. The give-up is terminal (no infinite retry) but not+ // replayable — exactly master's pre-recovery behavior.+ expect(result.poisonedIds).toEqual([id])+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)).toHaveLength(0)++ const rows = await cyclotronPool.query('SELECT status FROM cyclotron_jobs WHERE id = $1', [id])+ expect(rows.rowCount).toBe(1)+ expect(rows.rows[0].status).toBe('failed')+ })+})diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex e616f3de56b4..f5beea7ef5a6 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -38,6 +38,7 @@ import { CdpPrecalculatedFiltersConsumer } from './cdp/consumers/cdp-precalculatimport { CdpRerunWorkerConsumer } from './cdp/consumers/cdp-rerun-worker.consumer'import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'import { CdpProducerName } from './cdp/outputs/producers'+import { createCdpOutputsRegistry } from './cdp/outputs/registry'import { CyclotronV2JanitorService, CyclotronV2Manager, CyclotronV2Worker } from './cdp/services/cyclotron-v2'import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-schedule.service'import { HOGFLOW_BATCH_RESOLVE_QUEUE } from './cdp/services/hogflows/batch-resolver.types'@@ -47,6 +48,7 @@ import { CyclotronJobQueuePostgres } from './cdp/services/job-queue/job-queue-poimport { 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'+import { HogInvocationResultsService } from './cdp/services/monitoring/hog-invocation-results.service'import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rate-limiter-valkey-pool'import { RateLimiterService } from './cdp/services/rate-limiter/rate-limiter.service'import { EncryptedFields } from './cdp/utils/encryption-utils'@@ -107,13 +109,21 @@ export class PluginServer implements NodeServer {capabilities.cdpHogflowSubscriptionMatcher ||capabilities.cdpRerunWorker)+ // The janitor records poison-pill give-ups as failed invocation results,+ // so it needs the Kafka producer registry — but NOT createCdpSharedServices+ // (persons/geoip/integrations), which the minimal janitor deployment isn't+ // provisioned for (DATABASE_URL=NOT_REQUIRED, personhog off). Gate only the+ // producer on the janitor capability.+ const needsCdpProducer = needsCdp || capabilities.cdpCyclotronV2Janitor// 1. Shared infrastructure (always needed)const { teamManager } = await this.createSharedInfrastructure()// 2. Services shared by CDP (geoip, repos, encryption)let cdpServices: Awaited<ReturnType<typeof this.createCdpSharedServices>> | undefined- if (needsCdp) {+ if (needsCdpProducer) {this.cdpProducerRegistry = await createCdpProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)+ }+ if (needsCdp) {cdpServices = await this.createCdpSharedServices()}@@ -245,18 +255,27 @@ export class PluginServer implements NodeServer {throw new Error('CYCLOTRON_NODE_DATABASE_URL not configured but required for CyclotronV2JanitorService')}serviceLoaders.push(async () => {- const janitor = new CyclotronV2JanitorService({- pool: {- dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL!,- maxConnections: this.config.CYCLOTRON_NODE_MAX_CONNECTIONS,- idleTimeoutMs: this.config.CYCLOTRON_NODE_IDLE_TIMEOUT_MS,+ // Build a results service so the janitor can record poison-pill+ // give-ups as failed, replayable invocation results before+ // deleting the cyclotron row.+ const outputs = createCdpOutputsRegistry().build(this.cdpProducerRegistry!, this.config)+ const invocationResults = new HogInvocationResultsService(outputs, this.config)+ const janitor = new CyclotronV2JanitorService(+ {+ pool: {+ dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL!,+ maxConnections: this.config.CYCLOTRON_NODE_MAX_CONNECTIONS,+ idleTimeoutMs: this.config.CYCLOTRON_NODE_IDLE_TIMEOUT_MS,+ },+ cleanupBatchSize: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_BATCH_SIZE,+ cleanupIntervalMs: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_INTERVAL_MS,+ stallTimeoutMs: this.config.CYCLOTRON_NODE_JANITOR_STALL_TIMEOUT_MS,+ maxTouchCount: this.config.CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT,+ cleanupGraceMs: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS,+ poisonRecoveryEnabled: this.config.CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED,},- cleanupBatchSize: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_BATCH_SIZE,- cleanupIntervalMs: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_INTERVAL_MS,- stallTimeoutMs: this.config.CYCLOTRON_NODE_JANITOR_STALL_TIMEOUT_MS,- maxTouchCount: this.config.CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT,- cleanupGraceMs: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS,- })+ invocationResults+ )await janitor.start()return janitor.service})