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): make hog flow reruns resume instead of re-sending (#70792)

Daniel Marchukf08dc3f8e624
diff --git a/nodejs/src/cdp/rerun/rerun-e2e.test.ts b/nodejs/src/cdp/rerun/rerun-e2e.test.ts
index 2dfb6b0d668b..e19d5c030253 100644
--- a/nodejs/src/cdp/rerun/rerun-e2e.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-e2e.test.ts
@@ -17,9 +17,16 @@ import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, Team } from '../../types'
+import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
-import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'
+import {
+ insertHogFunction as _insertHogFunction,
+ createHogExecutionGlobals,
+ insertHogFunctionTemplate,
+} from '../_tests/fixtures'
+import { insertHogFlow } from '../_tests/fixtures-hogflows'
import { CdpConsumerBaseDeps } from '../consumers/cdp-base.consumer'
+import { CdpCyclotronWorkerHogFlow } from '../consumers/cdp-cyclotron-worker-hogflow.consumer'
import { CdpCyclotronWorker } from '../consumers/cdp-cyclotron-worker.consumer'
import { CdpEventsConsumer } from '../consumers/cdp-events.consumer'
import { CdpRerunWorkerConsumer } from '../consumers/cdp-rerun-worker.consumer'
@@ -126,6 +133,7 @@ describe('CDP hog invocation rerun e2e', () => {
let mockProducerObserver: KafkaProducerObserver
let eventsConsumer: CdpEventsConsumer
let cyclotronWorker: CdpCyclotronWorker
+ let hogflowWorker: CdpCyclotronWorkerHogFlow
let rerunManager: RerunJobManager
let rerunWorker: CdpRerunWorkerConsumer
let kafkaQueue: CyclotronJobQueueKafka
@@ -259,6 +267,7 @@ describe('CDP hog invocation rerun e2e', () => {
await Promise.all([
eventsConsumer?.stop().catch(() => undefined),
cyclotronWorker?.stop().catch(() => undefined),
+ hogflowWorker?.stop().catch(() => undefined),
rerunWorker?.stop().catch(() => undefined),
rerunManager?.disconnect().catch(() => undefined),
])
@@ -521,4 +530,143 @@ describe('CDP hog invocation rerun e2e', () => {
const rerunBody = String((ourCalls[ourCalls.length - 1] as any)[1]?.body ?? '')
expect(rerunBody).toContain('foo=from-event')
})
+
+ it('reruns a multi-action hog flow by resuming, not restarting, so completed actions do not re-fire', async () => {
+ // The hog-flow counterpart to the hog_function reruns above, and the core
+ // guard for #70792: a hog_function rerun re-executes the whole function
+ // (fetch fires again, by design), but a hog FLOW rerun must RESUME from
+ // where the recorded run left off — never restart from the trigger and
+ // re-run already-completed actions. A completed flow's recorded state
+ // sits at `exit`, so its rerun resumes there and the fetch action never
+ // fires a second time. Pre-#70792 the rehydration dropped `currentAction`,
+ // the flow restarted from the trigger, and the fetch re-fired — the
+ // double-send this proves is gone. Distinct URL isolates the flow's fetch
+ // from the beforeEach hog_function that also matches this event.
+ const FLOW_WEBHOOK_URL = 'https://example.com/flow-resume-webhook'
+
+ mockFetch.mockResolvedValue({
+ status: 200,
+ json: () => Promise.resolve({ ok: true }),
+ text: () => Promise.resolve('{"ok":true}'),
+ headers: { 'Content-Type': 'application/json' },
+ dump: () => Promise.resolve(),
+ })
+
+ // The flow's function action runs a template, not inline hog — insert the same
+ // fetch template the workflows-e2e suite uses.
+ await insertHogFunctionTemplate(hub.postgres, {
+ id: 'template-rerun-e2e-fetch',
+ name: 'Rerun E2E Fetch',
+ code: `
+ let res := fetch(inputs.url, {'method': inputs.method});
+ print('Fetch result:', res.status);
+ `,
+ inputs_schema: [
+ { key: 'url', type: 'string', required: true },
+ { key: 'method', type: 'string', required: false },
+ ],
+ })
+
+ const flow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ function_1: {
+ type: 'function',
+ config: {
+ template_id: 'template-rerun-e2e-fetch',
+ inputs: { url: { value: FLOW_WEBHOOK_URL }, method: { value: 'POST' } },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'function_1', type: 'continue' },
+ { from: 'function_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, flow)
+
+ // The hog-flow worker polls the same postgres-v2 backend the events consumer
+ // routes flows to (hogflowQueue in beforeEach).
+ hogflowWorker = new CdpCyclotronWorkerHogFlow(hub, cdpDeps, postgresV2Queue)
+ await hogflowWorker.start()
+
+ // ── 1. Original flow runs to completion — fetch fires exactly once ──────────
+ const { backgroundTask } = await eventsConsumer.processBatch([globals])
+ await backgroundTask
+
+ await waitForExpect(() => {
+ expect(mockFetch.mock.calls.filter(([url]) => String(url) === FLOW_WEBHOOK_URL).length).toBe(1)
+ }, 15_000)
+
+ // Terminal 'succeeded' hog_flow row lands in ClickHouse via Kafka -> MV.
+ await waitForExpect(async () => {
+ const rows = await clickhouse.query<PersistedRow>(
+ `SELECT invocation_id, status, is_retry, function_kind
+ FROM hog_invocation_results
+ WHERE team_id = ${team.id} AND function_id = '${flow.id}' AND status = 'succeeded'`
+ )
+ expect(rows.length).toBeGreaterThanOrEqual(1)
+ }, 30_000)
+
+ const originalRows = await clickhouse.query<PersistedRow>(
+ `SELECT invocation_id, status, is_retry, function_kind
+ FROM hog_invocation_results
+ WHERE team_id = ${team.id} AND function_id = '${flow.id}' AND status = 'succeeded'`
+ )
+ expect(originalRows[0].function_kind).toBe('hog_flow')
+ expect(originalRows[0].is_retry).toBe(0)
+ const originalInvocationId = originalRows[0].invocation_id
+
+ // ── 2. Mimic Django POST /rerun for the flow, scoped to this invocation ─────
+ const windowStart = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
+ const windowEnd = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
+ const rerunJobId = await rerunManager.enqueue(team.id, 'hog_flow', flow.id, {
+ filter: {
+ window_start: windowStart,
+ window_end: windowEnd,
+ status: ['succeeded'],
+ invocation_ids: [originalInvocationId],
+ },
+ })
+
+ // ── 3. Rerun worker drains the wrapper job (hog_flow -> postgres-v2) ────────
+ rerunWorker = new CdpRerunWorkerConsumer(
+ { ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres' },
+ cdpDeps,
+ { hog_function: kafkaQueue, hog_flow: postgresV2Queue }
+ )
+ await rerunWorker.start()
+
+ await waitForExpect(async () => {
+ const res = await nodeAssertPool.query('SELECT status FROM cyclotron_jobs WHERE id = $1', [rerunJobId])
+ expect(res.rows[0]?.status).toBe('completed')
+ }, 30_000)
+
+ // ── 4. Rerun invocation flows back through the real hog-flow worker ─────────
+ // Wait for the rerun's terminal row (is_retry=1) so we know it fully executed
+ // — by this point it would have re-fired the fetch if it were restarting.
+ await waitForExpect(async () => {
+ const rows = await clickhouse.query<PersistedRow>(
+ `SELECT invocation_id, status, is_retry, function_kind
+ FROM hog_invocation_results
+ WHERE team_id = ${team.id}
+ AND function_id = '${flow.id}'
+ AND invocation_id = '${originalInvocationId}'
+ AND is_retry = 1`
+ )
+ expect(rows.length).toBeGreaterThanOrEqual(1)
+ }, 30_000)
+
+ // ── 5. The resume ran nothing already done: the fetch is still at ONE call ──
+ // Restart-from-trigger (the pre-#70792 bug) would make this 2.
+ expect(mockFetch.mock.calls.filter(([url]) => String(url) === FLOW_WEBHOOK_URL).length).toBe(1)
+ })
})
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
new file mode 100644
index 000000000000..312c22ad01fb
--- /dev/null
+++ b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts
@@ -0,0 +1,138 @@
+import { ClickHouseClient } from '@clickhouse/client'
+import { DateTime } from 'luxon'
+
+import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'
+import { CyclotronJobQueuePostgresV2 } from '../services/job-queue/job-queue-postgres-v2'
+import { JobQueue } from '../services/job-queue/job-queue.interface'
+import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'
+import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
+import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'
+import { CyclotronJobInvocationHogFlow } from '../types'
+import { RerunJobState } from './rerun-job.types'
+import { RerunPaginatorService } from './rerun-paginator.service'
+
+// A poisoned wait_until_condition the janitor gave up on is recorded with the
+// FINAL flow state in `invocation_globals` — including `currentAction`, which is
+// where the executor resumes from. If rerun rehydration dropped it, the flow
+// would restart from the trigger and re-send emails that already went out. These
+// tests pin the fix: the rehydrated invocation carries `currentAction` forward,
+// so replay resumes after the already-completed actions.
+describe('RerunPaginatorService replay fidelity (hog_flow)', () => {
+ const teamId = 42
+ const functionId = 'flow-1'
+
+ function fakeClickhouse(rows: unknown[]): ClickHouseClient {
+ return {
+ query: jest.fn().mockResolvedValue({ json: () => Promise.resolve(rows) }),
+ } as unknown as ClickHouseClient
+ }
+
+ function buildPaginator(
+ clickhouse: ClickHouseClient,
+ hogFlowQueue: jest.Mocked<CyclotronJobQueuePostgresV2>
+ ): RerunPaginatorService {
+ const hogFlowManager = {
+ getHogFlow: jest.fn().mockResolvedValue({ id: functionId, team_id: teamId, variables: [] }),
+ } as unknown as jest.Mocked<HogFlowManagerService>
+ const hogFunctionManager = {
+ getHogFunction: jest.fn().mockResolvedValue(null),
+ } as unknown as jest.Mocked<HogFunctionManagerService>
+ const lifecycle = {
+ queueLifecycleRow: jest.fn(),
+ queueRerunWrapperRow: jest.fn(),
+ flush: jest.fn().mockResolvedValue(undefined),
+ dropQueuedRowsFor: jest.fn(),
+ } as unknown as jest.Mocked<HogInvocationResultsService>
+ const monitoring = {
+ queueLogs: jest.fn(),
+ flush: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<HogFunctionMonitoringService>
+
+ return new RerunPaginatorService(
+ clickhouse,
+ hogFunctionManager,
+ hogFlowManager,
+ lifecycle,
+ { hog_function: {} as unknown as JobQueue, hog_flow: hogFlowQueue },
+ monitoring,
+ 10000
+ )
+ }
+
+ const state: RerunJobState = {
+ function_kind: 'hog_flow',
+ function_id: functionId,
+ request: { filter: { window_start: '2026-01-01T00:00:00Z', window_end: '2027-01-01T00:00:00Z' } },
+ progress: { queued: 0, skipped: 0, done: false },
+ }
+
+ it('restores currentAction and personId so a partially-run flow resumes instead of restarting', async () => {
+ const persistedState = {
+ event: { uuid: 'evt-1', distinct_id: 'd-1', properties: {}, timestamp: '2026-06-01T09:00:00Z' },
+ actionStepCount: 3,
+ variables: { ticket_id: '123' },
+ // The flow had already advanced to (and parked at) the wait step.
+ currentAction: { id: 'wait_condition', startedAtTimestamp: 999 },
+ personId: 'person-1',
+ }
+ const rows = [
+ {
+ invocation_id: 'inv-1',
+ parent_run_id: 'run-1',
+ attempts: 0,
+ last_scheduled_at: '2026-06-01 09:00:00.000000',
+ first_scheduled_at: '2026-06-01 09:00:00.000000',
+ // decodeInvocationGlobals treats a leading '{' as raw JSON.
+ invocation_globals: JSON.stringify(persistedState),
+ },
+ ]
+
+ const hogFlowQueue = {
+ queueInvocations: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<CyclotronJobQueuePostgresV2>
+
+ const paginator = buildPaginator(fakeClickhouse(rows), hogFlowQueue)
+ await paginator.processPage(teamId, state, { jobId: 'rerun-1', createdAt: DateTime.now() })
+
+ expect(hogFlowQueue.queueInvocations).toHaveBeenCalledTimes(1)
+ const [enqueued, opts] = hogFlowQueue.queueInvocations.mock.calls[0]
+ expect(opts).toEqual({ overwriteExisting: true })
+ const invocation = enqueued[0] as CyclotronJobInvocationHogFlow
+ expect(invocation.id).toBe('inv-1')
+ // The resume point and per-actor context survive the round-trip.
+ expect(invocation.state?.currentAction).toEqual(persistedState.currentAction)
+ expect(invocation.state?.personId).toBe('person-1')
+ expect(invocation.state?.actionStepCount).toBe(3)
+ expect(invocation.state?.variables).toEqual({ ticket_id: '123' })
+ // Sticky rerun counter still increments so max_attempts guards apply.
+ expect(invocation.state?.rerunAttempts).toBe(1)
+ })
+
+ it('leaves currentAction undefined for a flow that never progressed (fresh start is correct there)', async () => {
+ const persistedState = {
+ event: { uuid: 'evt-2', distinct_id: 'd-2', properties: {}, timestamp: '2026-06-01T09:00:00Z' },
+ actionStepCount: 0,
+ variables: {},
+ }
+ const rows = [
+ {
+ invocation_id: 'inv-2',
+ parent_run_id: '',
+ attempts: 0,
+ last_scheduled_at: '2026-06-01 09:00:00.000000',
+ first_scheduled_at: '2026-06-01 09:00:00.000000',
+ invocation_globals: JSON.stringify(persistedState),
+ },
+ ]
+
+ const hogFlowQueue = {
+ queueInvocations: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<CyclotronJobQueuePostgresV2>
+
+ const paginator = buildPaginator(fakeClickhouse(rows), hogFlowQueue)
+ await paginator.processPage(teamId, state, { jobId: 'rerun-2', createdAt: DateTime.now() })
+
+ const invocation = hogFlowQueue.queueInvocations.mock.calls[0][0][0] as CyclotronJobInvocationHogFlow
+ expect(invocation.state?.currentAction).toBeUndefined()
+ })
+})
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
index 439bfd8b537f..79be227ea0b5 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
@@ -128,6 +128,52 @@ describe('RerunPaginatorService integration', () => {
}, 30_000)
}
+ // Produce a raw lifecycle row with a chosen (here: undecodable) invocation_globals,
+ // bypassing the seeding service so we can exercise the paginator's per-row
+ // rehydration-failure path — a poison-pill record whose stored globals can't be
+ // decoded must be skipped, not abort the whole recovery batch.
+ const seedRawRow = async (invocationId: string, invocationGlobals: string): Promise<void> => {
+ await kafkaProducer.queueMessages({
+ topic: KAFKA_HOG_INVOCATION_RESULTS,
+ messages: [
+ {
+ key: invocationId,
+ value: JSON.stringify({
+ team_id: team.id,
+ function_kind: 'hog_function',
+ function_id: hogFunction.id,
+ invocation_id: invocationId,
+ parent_run_id: '',
+ status: 'failed',
+ attempts: 0,
+ is_retry: 0,
+ scheduled_at: DateTime.utc().toFormat("yyyy-MM-dd HH:mm:ss.SSS'000'"),
+ started_at: null,
+ finished_at: null,
+ duration_ms: null,
+ error_kind: 'janitor_poison_pill',
+ error_message: 'poison pill',
+ event_uuid: '',
+ distinct_id: '',
+ person_id: '',
+ invocation_globals: invocationGlobals,
+ version: String(BigInt(Date.now()) * 1000n),
+ is_deleted: 0,
+ }),
+ },
+ ],
+ })
+ await kafkaProducer.flush()
+ seededCount += 1
+ await waitForExpect(async () => {
+ const got = await clickhouse.query<{ c: number }>(
+ `SELECT count() AS c FROM hog_invocation_results
+ WHERE team_id = ${team.id} AND invocation_id = '${invocationId}'`
+ )
+ expect(Number(got[0]?.c ?? 0)).toBeGreaterThanOrEqual(1)
+ }, 30_000)
+ }
+
beforeAll(async () => {
MockKafkaProducerWrapper.create = jest.fn((...args: any[]) => ActualKafkaProducerWrapper.create(...args))
await resetKafka()
@@ -312,6 +358,34 @@ describe('RerunPaginatorService integration', () => {
expect(enqueued).toHaveLength(1)
expect(enqueued[0].state.globals).not.toHaveProperty('inputs')
})
+
+ it('skips a record that fails to rehydrate and still re-enqueues the rest of the batch', async () => {
+ await seedRows([{ invocation_id: 'inv-good', status: 'failed', error: new Error('5xx') }])
+ await seedRawRow('inv-bad', 'not-a-decodable-globals-blob')
+
+ const state = buildState({
+ request: {
+ filter: {
+ window_start: '2026-01-01T00:00:00Z',
+ window_end: '2027-01-01T00:00:00Z',
+ invocation_ids: ['inv-good', 'inv-bad'],
+ },
+ },
+ })
+
+ const { state: next } = await paginator.processPage(team.id, state, {
+ jobId: 'test-rerun-job',
+ createdAt: DateTime.now(),
+ })
+
+ // The undecodable record is skipped, not fatal — the good one still re-enqueues.
+ const enqueued = hogQueue.queueInvocations.mock.calls.flatMap(
+ (c) => c[0] as CyclotronJobInvocationHogFunction[]
+ )
+ expect(enqueued.map((i) => i.id)).toEqual(['inv-good'])
+ expect(next.progress.queued).toBe(1)
+ expect(next.progress.skipped).toBeGreaterThanOrEqual(1)
+ })
})
describe('by-filter mode', () => {
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index 03bc0d6c9d77..42e3117cc7f0 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -663,6 +663,16 @@ export class RerunPaginatorService {
event: eventForFilter,
actionStepCount: persistedState.actionStepCount ?? 0,
variables: persistedState.variables ?? {},
+ // Restore where the flow had progressed to. The executor resumes
+ // from `currentAction` (via ensureCurrentAction); without it the
+ // flow restarts from the trigger and re-runs already-completed
+ // actions — re-sending emails that already went out. Carrying it
+ // forward makes replay of a partially-run flow (e.g. a poisoned
+ // wait_until_condition the janitor gave up on) resume safely.
+ // `personId` is carried for the same reason — the worker needs it
+ // to reload person data for batch/manual triggers on resume.
+ currentAction: persistedState.currentAction,
+ personId: persistedState.personId,
// Sticky rerun counter — mirror the hog function path so the
// lifecycle row producer can derive `attempts` / `is_retry`
// for flows too, and the `max_attempts` guard actually trips.
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index 25de57614c42..3d2d7b7a2054 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -202,6 +202,61 @@ describe('Hogflow Executor', () => {
.build()
})
+ it('resuming past a completed action does not re-execute it (no double-send on recovery)', async () => {
+ // A recovered poison-pill run resumes from where it stalled. currentAction
+ // sits AFTER function_id_1 (which does a fetch), so replay must resume at
+ // exit and must NOT re-run that fetch — otherwise a recovered flow re-sends
+ // an email/webhook that already went out.
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ properties: {
+ name: 'John Doe',
+ },
+ timestamp: '2026-01-30T20:20:20.200Z',
+ },
+ })
+ invocation.state.currentAction = {
+ id: 'exit',
+ startedAtTimestamp: DateTime.now().toMillis(),
+ }
+
+ const result = await executor.execute(invocation)
+
+ expect(result.finished).toBe(true)
+ expect(result.invocation.state.currentAction?.id).toBe('exit')
+ // The fetch-doing action before the resume point must not run again.
+ expect(mockFetch).toHaveBeenCalledTimes(0)
+ expect(result.logs.map((log) => log.message)).not.toContain('Executing action [Action:function_id_1]')
+ })
+
+ it('resuming a rerun onto an action removed by a later flow edit fails safe without re-running anything', async () => {
+ // #70792 restores currentAction on rerun. If the flow was edited after the run
+ // recorded its globals and the resume-point action was deleted, ensureCurrentAction
+ // can't find the id. The safe outcome is a finished, errored result — never a
+ // restart from the trigger (which would re-send) and never a hang.
+ const invocation = createExampleHogFlowInvocation(hogFlow, {
+ event: {
+ ...createHogExecutionGlobals().event,
+ properties: {
+ name: 'John Doe',
+ },
+ },
+ })
+ invocation.state.currentAction = {
+ id: 'action_removed_by_edit',
+ startedAtTimestamp: DateTime.now().toMillis(),
+ }
+
+ const result = await executor.execute(invocation)
+
+ expect(result.finished).toBe(true)
+ expect(result.error).toContain('action_removed_by_edit')
+ // Nothing already done gets re-run: the fetch-doing action never executes.
+ expect(mockFetch).toHaveBeenCalledTimes(0)
+ expect(result.logs.map((log) => log.message)).not.toContain('Executing action [Action:function_id_1]')
+ })
+
it('can execute a simple hogflow', async () => {
const invocation = createExampleHogFlowInvocation(hogFlow, {
event: {
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.ts b/nodejs/src/cdp/utils/hog-function-filtering.ts
index 1d07f0deadb9..0cebb18e7800 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.ts
@@ -226,7 +226,11 @@ export function convertClickhouseRawEventToFilterGlobals(event: RawClickHouseEve
export function convertToHogFunctionFilterGlobal(
globals: Pick<HogFunctionInvocationGlobals, 'event' | 'person' | 'groups' | 'variables'>
): HogFunctionFilterGlobals {
- const elementsChain = globals.event.elements_chain ?? globals.event.properties['$elements_chain']
+ // Rehydrated invocation events (e.g. a rerun of a janitor-recorded poison pill,
+ // whose stored globals are trimmed) can arrive without `properties` — default it
+ // rather than dereferencing undefined.
+ const properties = globals.event.properties ?? {}
+ const elementsChain = globals.event.elements_chain ?? properties['$elements_chain']
const response: HogFunctionFilterGlobals = {
event: globals.event.event,
@@ -237,7 +241,7 @@ export function convertToHogFunctionFilterGlobal(
elements_chain_ids: [] as string[],
elements_chain_elements: [] as string[],
timestamp: globals.event.timestamp,
- properties: globals.event.properties,
+ properties,
person: globals.person ? { id: globals.person.id, properties: globals.person.properties } : null,
pdi: globals.person
? {