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): don't record poisoned rerun wrappers as replayable invocations (#72747)

Daniel Marchuk24c056530aaa
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 7305ebbd61ac..4959c9929a74 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -1769,7 +1769,10 @@ describe('Cyclotron V2', () => {
const defaults = {
team_id: 1,
function_id: null,
- queue_name: QUEUE,
+ // Default to a real invocation queue so a poisoned genuine invocation is recorded.
+ // The janitor only records give-ups on invocation queues; anything else is a
+ // wrapper/meta job that's dropped without a record (see WRAPPER drop tests below).
+ queue_name: 'hogflow',
status: 'available',
priority: 0,
scheduled: new Date(),
@@ -1985,6 +1988,57 @@ describe('Cyclotron V2', () => {
expect(await totalJobCount()).toBe(0)
})
+ // Both meta/wrapper queues share cyclotron_jobs with real invocations and
+ // stamp function_id to a target function, so both must be dropped without a
+ // record — else the autodrain replays a real flow with fabricated globals.
+ // 'some_future_meta_queue' is an unknown, non-invocation queue: it guards the allow-list's
+ // fail-safe. Under the old deny-list a queue nobody listed would be RECORDED as a replayable
+ // hog_flow (the autodrain would then replay a phantom flow) — with the allow-list any queue
+ // not in CYCLOTRON_INVOCATION_JOB_QUEUES is dropped without a record by default.
+ it.each(['rerun', 'hogflow_batch_resolve', 'some_future_meta_queue'])(
+ 'drops a poisoned %s wrapper without recording it, still records real invocations',
+ async (wrapperQueue) => {
+ const staleHeartbeat = new Date(Date.now() - 60_000)
+ const wrapperId = uuidv7()
+ const invocationId = uuidv7()
+ // A poisoned WRAPPER job and a genuine poisoned invocation, same sweep.
+ await insertRawJob({
+ id: wrapperId,
+ function_id: uuidv7(),
+ queue_name: wrapperQueue,
+ status: 'running',
+ lock_id: uuidv7(),
+ last_heartbeat: staleHeartbeat,
+ janitor_touch_count: 3,
+ })
+ await insertRawJob({
+ id: invocationId,
+ 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()
+
+ // The wrapper is dropped with NO replay record — recording it would let
+ // the autodrain rediscover it as a hog_flow and replay a real flow with
+ // fabricated globals. Only the genuine invocation is recorded.
+ expect(recordTerminalFailureDurably).toHaveBeenCalledTimes(1)
+ expect(recordTerminalFailureDurably).toHaveBeenCalledWith(
+ expect.objectContaining({ id: invocationId }),
+ expect.anything()
+ )
+ expect(result.poisonedIds).toEqual([invocationId])
+ // Both cyclotron rows are gone — the wrapper is given up on, just untraced.
+ 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()
diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
index cadf6d8348a3..f63020db9894 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
@@ -4,7 +4,7 @@ import { Counter, Gauge } from 'prom-client'
import { logger } from '~/common/utils/logger'
-import { CyclotronJobInvocationHogFlow } from '../../types'
+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'
@@ -14,6 +14,17 @@ import { CyclotronV2CleanupResult, CyclotronV2DequeuedJob, CyclotronV2JanitorCon
// exactly these give-ups from the rerun tooling (rerun filter `error_kind`).
export const JANITOR_POISON_PILL_ERROR_KIND = 'janitor_poison_pill'
+// Only jobs on a real invocation queue carry a replayable invocation. Everything else on this
+// shared cyclotron_jobs table (the rerun + batch-resolve wrappers, and any future meta queue) has a
+// `function_id` pointing at a target function and a `state` that is not an invocation — recording
+// one as a give-up would tag it `function_kind='hog_flow'` and let the autodrain replay a real flow
+// with fabricated globals (see recordAndDeletePoisonPills). So the janitor records give-ups only for
+// this allow-list and drops everything else without a record. Keying off the canonical allow-list
+// (it *is* the `CyclotronJobQueueKind` type) is deliberately fail-safe: a new meta queue is dropped
+// by default, and a new invocation queue has to be added to this list to compile — no hand-kept
+// deny-list to fall out of sync (which is how the batch-resolve queue was missed originally).
+const INVOCATION_QUEUE_NAMES: string[] = [...CYCLOTRON_INVOCATION_JOB_QUEUES]
+
// The first stall gets only this small jittered delay (not the full exponential
// base), so a transient stall — a worker restart/deploy, where a healthy worker
// should pick the job right back up — recovers in seconds rather than waiting a
@@ -42,6 +53,11 @@ const janitorGiveUpSkippedCounter = new Counter({
help: 'Poison pills the janitor could not record a recovery row for, so kept (not deleted)',
})
+const janitorWrapperDroppedCounter = new Counter({
+ name: 'cdp_cyclotron_v2_janitor_wrapper_dropped',
+ help: 'Poisoned wrapper/meta jobs dropped without a replay record (a wrapper is not a replayable invocation)',
+})
+
const janitorRunCounter = new Counter({
name: 'cdp_cyclotron_v2_janitor_runs',
help: 'Number of janitor cleanup runs completed',
@@ -241,6 +257,15 @@ export class CyclotronV2Janitor {
private async recordAndDeletePoisonPills(): Promise<string[]> {
const heartbeatCutoff = new Date(Date.now() - this.stallTimeoutMs)
+ // Wrapper/meta jobs (rerun, batch-resolve, any future non-invocation queue) share this table.
+ // A wrapper is not a replayable invocation — recording one as a `failed` result would give it
+ // `function_kind='hog_flow'` with the target's `function_id` (poisonRowToInvocation always tags
+ // hogFlow), making it indistinguishable from a genuine poisoned flow, and the autodrain would
+ // then rediscover and replay a real flow with fabricated globals. So give up on anything not on
+ // an invocation queue separately: delete it with NO record. This is self-healing — the work a
+ // wrapper was driving is re-derived on its next run.
+ await this.dropWrapperPoisonPills(heartbeatCutoff)
+
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,
@@ -249,10 +274,11 @@ export class CyclotronV2Janitor {
WHERE status = 'running'
AND COALESCE(last_heartbeat, $1) <= $1
AND janitor_touch_count >= $2
+ AND queue_name = ANY($4::text[])
ORDER BY last_transition ASC
LIMIT $3
FOR UPDATE SKIP LOCKED`,
- [heartbeatCutoff, this.maxTouchCount, this.cleanupBatchSize]
+ [heartbeatCutoff, this.maxTouchCount, this.cleanupBatchSize, INVOCATION_QUEUE_NAMES]
)
if (result.rows.length === 0) {
@@ -322,6 +348,46 @@ export class CyclotronV2Janitor {
return deletedIds
}
+ /**
+ * Give up on poisoned wrapper/meta jobs — anything not on an invocation queue (rerun,
+ * batch-resolve, any future meta queue) — by deleting them with no replay record. See the
+ * rationale in recordAndDeletePoisonPills. A wrapper is not a replayable invocation, so there is
+ * nothing meaningful to record; dropping it is safe and self-healing (its work is re-derived on
+ * the next run).
+ */
+ private async dropWrapperPoisonPills(heartbeatCutoff: Date): Promise<number> {
+ // Bound the delete to cleanupBatchSize and pick rows via FOR UPDATE SKIP
+ // LOCKED, mirroring the genuine-poison-pill path below. This runs first in
+ // the tick: an unbounded delete could both lock a large row set and block on
+ // a row a worker/other janitor holds, stalling the whole tick before genuine
+ // pills get recorded. Skipping locked rows and capping the batch keeps the
+ // wrapper drain from starving the rest of the sweep — leftovers drain next tick.
+ const deleted = await this.pool.query<{ id: string }>(
+ `DELETE FROM cyclotron_jobs
+ WHERE id IN (
+ SELECT id FROM cyclotron_jobs
+ WHERE status = 'running'
+ AND queue_name <> ALL($1::text[])
+ AND COALESCE(last_heartbeat, $2) <= $2
+ AND janitor_touch_count >= $3
+ ORDER BY last_transition ASC
+ LIMIT $4
+ FOR UPDATE SKIP LOCKED
+ )
+ RETURNING id`,
+ [INVOCATION_QUEUE_NAMES, heartbeatCutoff, this.maxTouchCount, this.cleanupBatchSize]
+ )
+ const count = deleted.rows.length
+ if (count > 0) {
+ janitorWrapperDroppedCounter.inc(count)
+ logger.warn('CyclotronV2Janitor dropped poisoned wrapper jobs (no replay record — meta-job)', {
+ count,
+ ids: deleted.rows.map((r) => r.id),
+ })
+ }
+ return count
+ }
+
// 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