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): guard against malformed invocation globals in cyclotron-hog worker (#73076)

Meikel Ratz06066f01b0ba
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
index b6f91e69ade6..94e6b8e80592 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
@@ -88,6 +88,23 @@ export class CdpCyclotronWorker<
const hogFuncState = item.state as CyclotronJobInvocationHogFunction['state']
+ // Guard against malformed invocation state (globals present but missing
+ // project/event). Without this the unguarded derefs below throw an unhandled
+ // rejection that crash-loops the worker on a single poison-pill message,
+ // stalling the whole partition. Drop it instead so the batch can make progress.
+ if (!hogFuncState.globals?.project || !hogFuncState.globals?.event) {
+ logger.error('⚠️', 'Skipping invocation with malformed globals (missing project or event)', {
+ id: item.functionId,
+ })
+ captureException(new Error('Malformed hog function invocation globals: missing project or event'), {
+ tags: { functionId: item.functionId, teamId: String(item.teamId) },
+ })
+
+ failedInvocations.push(item)
+
+ return
+ }
+
await Promise.all([
this.groupsManager.addGroupsToGlobals(hogFuncState.globals),
!hogFuncState.globals.person
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
index 380a121b1281..bef853453192 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
@@ -258,6 +258,23 @@ describe('CdpCyclotronWorker', () => {
expect(dequeueInvocationsSpy).toHaveBeenCalledWith([invocation])
})
+ it.each([['project'], ['event']] as const)(
+ 'should DLQ a malformed invocation whose globals is missing %s instead of crashing',
+ async (field) => {
+ const dequeueInvocationsSpy = jest
+ .spyOn(processor['cyclotronJobQueue'], 'dequeueInvocations')
+ .mockResolvedValue(undefined)
+
+ const malformed = createExampleInvocation(fn, globals)
+ delete (malformed.state.globals as any)[field]
+
+ const results = await processor['loadHogFunctions']([malformed])
+
+ expect(results).toEqual([])
+ expect(dequeueInvocationsSpy).toHaveBeenCalledWith([malformed])
+ }
+ )
+
it('should skip a loaded function if it is disabled', async () => {
const fn2 = await insertHogFunction(
hub.postgres,
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
index 42e039c3cc8a..93a41cdb4468 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.routing.test.ts
@@ -159,7 +159,12 @@ describe('RerunPaginatorService queue routing', () => {
attempts: 0,
last_scheduled_at: '2026-01-01 00:00:00',
first_scheduled_at: '2026-01-01 00:00:00',
- invocation_globals: JSON.stringify({ event: { uuid: 'e1' } }),
+ // Well-formed globals so the rerunnable-type cases pass rehydration's
+ // schema validation — the type gate is what these tests exercise.
+ invocation_globals: JSON.stringify({
+ project: { id: 1, name: '', url: '' },
+ event: { uuid: 'e1', distinct_id: 'd1', properties: {} },
+ }),
}
return (webhookPaginator as any).rehydrateInvocation(1, 'hog_function', 'fn-1', row)
}
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index 6fba71da3ab4..af4fcfa217db 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -4,6 +4,7 @@ import { Counter } from 'prom-client'
import { logger } from '~/common/utils/logger'
+import { HogFunctionInvocationGlobalsSchema } from '../schema/cyclotron'
import { CyclotronJobConflictError } from '../services/cyclotron-v2'
import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'
import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'
@@ -606,6 +607,21 @@ export class RerunPaginatorService {
// rehydrates `groups`/`person` and the executor rebuilds `inputs`
// from the current hog function config, so the rerun runs against
// the latest config/secrets rather than a stored snapshot.
+ //
+ // Validate the shape before trusting it: a snapshot written by an
+ // older serializer (or otherwise drifted) can be missing
+ // project/event, which the worker dereferences unguarded — skip the
+ // row rather than re-enqueue a poison pill.
+ const parsed = HogFunctionInvocationGlobalsSchema.safeParse(parsedGlobals)
+ if (!parsed.success) {
+ logger.warn('⚠️', 'Skipping rerun of invocation with malformed persisted globals', {
+ functionId,
+ teamId,
+ invocation_id: row.invocation_id,
+ issues: parsed.error.issues.map((issue) => issue.path.join('.')),
+ })
+ return null
+ }
const persistedGlobals = parsedGlobals as HogFunctionInvocationGlobalsWithInputs
const invocation: CyclotronJobInvocationHogFunction = {
diff --git a/nodejs/src/cdp/schema/cyclotron.test.ts b/nodejs/src/cdp/schema/cyclotron.test.ts
new file mode 100644
index 000000000000..0c831dd3c0ee
--- /dev/null
+++ b/nodejs/src/cdp/schema/cyclotron.test.ts
@@ -0,0 +1,39 @@
+import { createHogExecutionGlobals } from '../_tests/fixtures'
+import { HogFunctionInvocationGlobalsSchema } from './cyclotron'
+
+describe('cyclotron schema', () => {
+ describe('HogFunctionInvocationGlobalsSchema', () => {
+ it('accepts well-formed globals', () => {
+ const globals = createHogExecutionGlobals({})
+ expect(HogFunctionInvocationGlobalsSchema.safeParse(globals).success).toBe(true)
+ })
+
+ it.each([['project'], ['event']] as const)('rejects globals missing %s (poison-pill shape)', (field) => {
+ const globals = createHogExecutionGlobals({}) as any
+ delete globals[field]
+ expect(HogFunctionInvocationGlobalsSchema.safeParse(globals).success).toBe(false)
+ })
+
+ it.each([
+ { mutation: (g: any) => (g.project.id = 'not-a-number'), desc: 'project.id is not a number' },
+ { mutation: (g: any) => delete g.project.url, desc: 'project.url is missing' },
+ { mutation: (g: any) => delete g.event.distinct_id, desc: 'event.distinct_id is missing' },
+ { mutation: (g: any) => delete g.event.properties, desc: 'event.properties is missing' },
+ ])('rejects when $desc', ({ mutation }) => {
+ const globals = createHogExecutionGlobals({}) as any
+ mutation(globals)
+ expect(HogFunctionInvocationGlobalsSchema.safeParse(globals).success).toBe(false)
+ })
+
+ it('passes through non-critical fields so reruns keep inputs/request', () => {
+ // The rerun path casts the validated globals to WithInputs and relies on
+ // extra fields surviving — a switch to a strict schema would silently
+ // strip them and break replay.
+ const globals = { ...createHogExecutionGlobals({}), inputs: { url: 'https://x' }, custom: 1 } as any
+ const parsed = HogFunctionInvocationGlobalsSchema.safeParse(globals)
+ expect(parsed.success).toBe(true)
+ expect((parsed as any).data.inputs).toEqual({ url: 'https://x' })
+ expect((parsed as any).data.custom).toBe(1)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/schema/cyclotron.ts b/nodejs/src/cdp/schema/cyclotron.ts
index 6c4fe185617f..2611234307d8 100644
--- a/nodejs/src/cdp/schema/cyclotron.ts
+++ b/nodejs/src/cdp/schema/cyclotron.ts
@@ -61,6 +61,30 @@ export const CyclotronInputMappingSchema = z.object({
filters: z.any().optional().nullable(),
})
+// The invariants the cyclotron-hog worker relies on when it enriches and
+// executes an invocation: `globals.project.{id,url}` and
+// `globals.event.{distinct_id,properties}` are dereferenced unguarded
+// downstream, so an invocation reconstructed without them is a poison pill.
+// Validate these rather than blind-casting a deserialized/rehydrated payload.
+// Everything else stays permissive (`passthrough`) so drift on non-critical
+// fields never rejects an otherwise-valid message.
+export const HogFunctionInvocationGlobalsSchema = z
+ .object({
+ project: z
+ .object({
+ id: z.number(),
+ url: z.string(),
+ })
+ .passthrough(),
+ event: z
+ .object({
+ distinct_id: z.string(),
+ properties: z.record(z.string(), z.unknown()),
+ })
+ .passthrough(),
+ })
+ .passthrough()
+
export type CyclotronJobInputSchemaType = z.infer<typeof CyclotronJobInputSchemaTypeSchema>
export type CyclotronInputType = z.infer<typeof CyclotronInputSchema>
diff --git a/nodejs/src/cdp/services/managers/groups-manager.service.test.ts b/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
index 2958b66b319d..52a8aa579959 100644
--- a/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
+++ b/nodejs/src/cdp/services/managers/groups-manager.service.test.ts
@@ -322,6 +322,23 @@ describe('Groups Manager', () => {
expect(mockFetchGroupsByKeys).not.toHaveBeenCalled()
})
+ it.each([['project'], ['event']] as const)(
+ 'does not throw when globals.%s is missing (poison-pill invocation)',
+ async (field) => {
+ // A malformed invocation whose state.globals is present but missing project/event
+ // must not crash the worker — otherwise it becomes a poison pill that crash-loops
+ // the cyclotron-hog consumer and stalls the partition it owns.
+ const globals = createHogExecutionGlobals({
+ groups: undefined,
+ event: { properties: { $groups: { GroupA: 'id-1' } } } as any,
+ })
+ delete (globals as any)[field]
+
+ await expect(groupsManager.addGroupsToGlobals(globals)).resolves.toBeUndefined()
+ expect(globals.groups).toEqual({})
+ }
+ )
+
it('respects clear() to reset all caches', async () => {
const globals1 = createHogExecutionGlobals({
groups: undefined,
diff --git a/nodejs/src/cdp/services/managers/groups-manager.service.ts b/nodejs/src/cdp/services/managers/groups-manager.service.ts
index a20a7eb9c99d..bdbe3a9f81d8 100644
--- a/nodejs/src/cdp/services/managers/groups-manager.service.ts
+++ b/nodejs/src/cdp/services/managers/groups-manager.service.ts
@@ -126,6 +126,14 @@ export class GroupsManagerService {
return
}
+ // A malformed invocation can arrive with globals present but missing project/event
+ // (e.g. partial state rehydration). Skip enrichment rather than dereferencing them —
+ // an unguarded throw here becomes an unhandled rejection that crash-loops the worker.
+ if (!globals.project || !globals.event) {
+ globals.groups = {}
+ return
+ }
+
globals.groups = await this.getGroupsForEvent(globals.project.id, globals.event.properties, globals.project.url)
}