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): stop re-runs of disabled functions from getting stuck running (#85712)

Harley Alexander7b3bd72a3699
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
index 60755e174837..fbb7942ad887 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
@@ -61,7 +61,11 @@ export class CdpCyclotronWorker<
invocations: CyclotronJobInvocation[]
): Promise<CyclotronJobInvocationHogFunction[]> {
const loadedInvocations: CyclotronJobInvocationHogFunction[] = []
- const failedInvocations: CyclotronJobInvocation[] = []
+ const failedInvocations: {
+ invocation: CyclotronJobInvocation | CyclotronJobInvocationHogFunction
+ errorKind: string
+ error: string
+ }[] = []
await Promise.all(
invocations.map(async (item) => {
@@ -71,7 +75,11 @@ export class CdpCyclotronWorker<
id: item.functionId,
})
- failedInvocations.push(item)
+ failedInvocations.push({
+ invocation: item,
+ errorKind: 'function_not_found',
+ error: 'The function could not be found, so this invocation was skipped.',
+ })
return
}
@@ -81,7 +89,21 @@ export class CdpCyclotronWorker<
id: item.functionId,
})
- failedInvocations.push(item)
+ failedInvocations.push({
+ // Attach the loaded function so the terminal 'failed' row serializes the
+ // real invocation globals instead of '{}'. The row wins the
+ // ReplacingMergeTree argMax over the earlier 'running' row, so without
+ // its globals the rerun paginator can't rehydrate the invocation and a
+ // re-run after re-enabling would silently skip. Fall back to the raw item
+ // when state globals are absent (nothing to preserve).
+ invocation: item.state?.globals
+ ? { ...item, state: item.state as CyclotronJobInvocationHogFunction['state'], hogFunction }
+ : item,
+ errorKind: hogFunction.deleted ? 'function_deleted' : 'function_disabled',
+ error: hogFunction.deleted
+ ? 'The function was deleted, so this invocation was skipped.'
+ : 'The function was disabled, so this invocation was skipped.',
+ })
return
}
@@ -100,7 +122,11 @@ export class CdpCyclotronWorker<
tags: { functionId: item.functionId, teamId: String(item.teamId) },
})
- failedInvocations.push(item)
+ failedInvocations.push({
+ invocation: item,
+ errorKind: 'malformed_invocation',
+ error: 'The invocation data was malformed, so it was skipped.',
+ })
return
}
@@ -133,7 +159,25 @@ export class CdpCyclotronWorker<
})
)
- await this.cyclotronJobQueue.dequeueInvocations(failedInvocations)
+ if (failedInvocations.length) {
+ // Record the terminal lifecycle row BEFORE dequeuing (same ordering as the
+ // janitor's poison-pill recovery). Dropping the job without one leaves the
+ // invocation stuck 'running' in the runs UI and permanently un-rerunnable.
+ const recorded = await Promise.all(
+ failedInvocations.map(({ invocation, errorKind, error }) =>
+ this.invocationResultsService.invocationResultsRowsService.recordTerminalFailureDurably(
+ invocation,
+ { errorKind, error }
+ )
+ )
+ )
+ // Keep any job whose terminal row could not be produced so a later fetch retries
+ // it, unless lifecycle recording is disabled (then there is no row to go stale).
+ const dequeueable = failedInvocations.filter(
+ (_, i) => recorded[i] || !this.config.HOG_INVOCATION_RESULTS_ENABLED
+ )
+ await this.cyclotronJobQueue.dequeueInvocations(dequeueable.map((x) => x.invocation))
+ }
return loadedInvocations
}
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
index 5d87cf60a379..9ee18e36bc7b 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
@@ -251,11 +251,22 @@ describe('CdpCyclotronWorker', () => {
const dequeueInvocationsSpy = jest
.spyOn(processor['cyclotronJobQueue'], 'dequeueInvocations')
.mockResolvedValue(undefined)
+ const recordTerminalFailureSpy = jest
+ .spyOn(
+ processor['invocationResultsService'].invocationResultsRowsService,
+ 'recordTerminalFailureDurably'
+ )
+ .mockResolvedValue(true)
const invocation = createExampleInvocation(fn, globals)
invocation.functionId = new UUIDT().toString()
const results = await processor.processInvocations([invocation])
expect(results).toEqual([])
expect(dequeueInvocationsSpy).toHaveBeenCalledWith([invocation])
+ // Without a terminal lifecycle row the runs UI shows the invocation as running forever
+ expect(recordTerminalFailureSpy).toHaveBeenCalledWith(
+ invocation,
+ expect.objectContaining({ errorKind: 'function_not_found' })
+ )
})
it.each([['project'], ['event']] as const)(
@@ -264,6 +275,12 @@ describe('CdpCyclotronWorker', () => {
const dequeueInvocationsSpy = jest
.spyOn(processor['cyclotronJobQueue'], 'dequeueInvocations')
.mockResolvedValue(undefined)
+ const recordTerminalFailureSpy = jest
+ .spyOn(
+ processor['invocationResultsService'].invocationResultsRowsService,
+ 'recordTerminalFailureDurably'
+ )
+ .mockResolvedValue(true)
const malformed = createExampleInvocation(fn, globals)
delete (malformed.state.globals as any)[field]
@@ -272,10 +289,23 @@ describe('CdpCyclotronWorker', () => {
expect(results).toEqual([])
expect(dequeueInvocationsSpy).toHaveBeenCalledWith([malformed])
+ expect(recordTerminalFailureSpy).toHaveBeenCalledWith(
+ malformed,
+ expect.objectContaining({ errorKind: 'malformed_invocation' })
+ )
}
)
- it('should skip a loaded function if it is disabled', async () => {
+ it('should skip a loaded function if it is disabled and record the terminal row with real globals', async () => {
+ const dequeueInvocationsSpy = jest
+ .spyOn(processor['cyclotronJobQueue'], 'dequeueInvocations')
+ .mockResolvedValue(undefined)
+ const recordTerminalFailureSpy = jest
+ .spyOn(
+ processor['invocationResultsService'].invocationResultsRowsService,
+ 'recordTerminalFailureDurably'
+ )
+ .mockResolvedValue(true)
const fn2 = await insertHogFunction(
hub.postgres,
team.id,
@@ -286,9 +316,45 @@ describe('CdpCyclotronWorker', () => {
enabled: false,
})
)
+ // Simulate a job as it arrives off the queue: state + globals present, but the
+ // hogFunction not yet loaded — loadHogFunctions is what attaches it. The fixture
+ // pre-attaches it, which would otherwise mask the lost-globals regression.
+ const { hogFunction: _unloaded, ...queued } = createExampleInvocation(fn2, globals)
+
+ const results = await processor['loadHogFunctions']([queued as CyclotronJobInvocationHogFunction])
+ expect(results).toEqual([])
+ expect(dequeueInvocationsSpy).toHaveBeenCalledWith([expect.objectContaining({ id: queued.id })])
+ // The terminal row must be built from a fully-shaped hog function invocation so its
+ // globals serialize to the real payload, not '{}'. Otherwise the row wins the
+ // ReplacingMergeTree argMax and the rerun paginator can't rehydrate it — the re-run
+ // after re-enabling the function would silently skip.
+ expect(recordTerminalFailureSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: queued.id,
+ hogFunction: expect.objectContaining({ id: fn2.id }),
+ state: expect.objectContaining({ globals: queued.state.globals }),
+ }),
+ expect.objectContaining({ errorKind: 'function_disabled' })
+ )
+ })
+
+ it('should keep the job for a later retry if the terminal row cannot be recorded', async () => {
+ hub.HOG_INVOCATION_RESULTS_ENABLED = true
+ const dequeueInvocationsSpy = jest
+ .spyOn(processor['cyclotronJobQueue'], 'dequeueInvocations')
+ .mockResolvedValue(undefined)
+ jest.spyOn(
+ processor['invocationResultsService'].invocationResultsRowsService,
+ 'recordTerminalFailureDurably'
+ ).mockResolvedValue(false)
+ const invocation2 = createExampleInvocation(fn, globals)
+ invocation2.functionId = new UUIDT().toString()
+
+ const results = await processor['loadHogFunctions']([invocation2])
- const results = await processor['loadHogFunctions']([createExampleInvocation(fn2, globals)])
expect(results).toEqual([])
+ // Dequeuing without the terminal row would recreate the stuck-'running' state
+ expect(dequeueInvocationsSpy).toHaveBeenCalledWith([])
})
describe('e2e lag metrics tracking', () => {
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index 1c924c8a783b..dc56af0ecdb1 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -1107,7 +1107,8 @@ class HogFunctionViewSet(
transformations during ingestion, `site_*` transpiled to client-side
JS). A re-enqueued invocation of one of those would never drain and
wedges the partition, so a rerun of a non-rerunnable type is rejected
- with a 400 here.
+ with a 400 here. A disabled function is rejected the same way: the
+ worker skips its invocations, so the rerun could never execute.
Because rerun replays historical event/person/group data, it requires
`person:read` and `group:read` on top of `hog_function:write`.
@@ -1124,6 +1125,10 @@ class HogFunctionViewSet(
status=400,
)
+ # The worker skips invocations of disabled functions, so an enqueued re-run could never execute.
+ if not hog_function.enabled:
+ raise serializers.ValidationError("This function is disabled. Enable it to re-run invocations.")
+
serializer = HogInvocationRerunRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 825d61a27559..ab3e7edae150 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -1935,8 +1935,27 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# The whole point: a non-rerunnable type must never reach the enqueue path.
mock_rerun.assert_not_called()
+ def test_rerun_rejected_when_function_disabled(self):
+ fn = HogFunction.objects.create(team=self.team, type="destination", hog="return event", enabled=False)
+
+ with patch("products.cdp.backend.api.hog_function.rerun_hog_invocations") as mock_rerun:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/{fn.id}/rerun/",
+ data={
+ "filter": {
+ "window_start": "2026-07-01T00:00:00Z",
+ "window_end": "2026-07-02T00:00:00Z",
+ }
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "disabled" in response.json()["detail"]
+ # The worker drops invocations of disabled functions, so the enqueue path must not be reached.
+ mock_rerun.assert_not_called()
+
def test_rerun_allowed_for_destination(self):
- fn = HogFunction.objects.create(team=self.team, type="destination", hog="return event")
+ fn = HogFunction.objects.create(team=self.team, type="destination", hog="return event", enabled=True)
with patch("products.cdp.backend.api.hog_function.rerun_hog_invocations") as mock_rerun:
mock_rerun.return_value = MagicMock(status_code=200, json=lambda: {"rerun_job_id": "job-1"})
diff --git a/products/cdp/frontend/generated/api.ts b/products/cdp/frontend/generated/api.ts
index 7a2a0dec05fc..f02874ece8bd 100644
--- a/products/cdp/frontend/generated/api.ts
+++ b/products/cdp/frontend/generated/api.ts
@@ -388,7 +388,8 @@ export const getHogFunctionsRerunCreateUrl = (projectId: string, id: string) =>
* transformations during ingestion, `site_*` transpiled to client-side
* JS). A re-enqueued invocation of one of those would never drain and
* wedges the partition, so a rerun of a non-rerunnable type is rejected
- * with a 400 here.
+ * with a 400 here. A disabled function is rejected the same way: the
+ * worker skips its invocations, so the rerun could never execute.
*
* Because rerun replays historical event/person/group data, it requires
* `person:read` and `group:read` on top of `hog_function:write`.
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index febe2618e4c4..56b84b08e9ec 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -1534,7 +1534,8 @@ export const HogFunctionsPublishCreateBody = /* @__PURE__ */ zod.object({
* transformations during ingestion, `site_*` transpiled to client-side
* JS). A re-enqueued invocation of one of those would never drain and
* wedges the partition, so a rerun of a non-rerunnable type is rejected
- * with a 400 here.
+ * with a 400 here. A disabled function is rejected the same way: the
+ * worker skips its invocations, so the rerun could never execute.
*
* Because rerun replays historical event/person/group data, it requires
* `person:read` and `group:read` on top of `hog_function:write`.