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): record a running row when a webhook or schedule triggers a workflow (#100904)

Meikel Ratzd7777b3c93d7
diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.ts
index 867a39006a05..498e93817d31 100644
--- a/nodejs/src/cdp/cdp-api.serial.test.ts
+++ b/nodejs/src/cdp/cdp-api.serial.test.ts
@@ -1597,6 +1597,57 @@ describe('CDP API', () => {
expect(mockQueueInvocations).toHaveBeenCalledTimes(1)
})
+ it('stamps the run start into the state before the invocation is queued', async () => {
+ // Snapshot at call time, so a stamp applied after queueInvocations does not count.
+ let stateWhenQueued: string | undefined
+ mockQueueInvocations.mockImplementation((invocations: any[]) => {
+ stateWhenQueued = JSON.stringify(invocations[0].state)
+ return Promise.resolve()
+ })
+ // `hub` is shared across this file, so the flag is restored rather than left on.
+ const resultsEnabled = hub.HOG_INVOCATION_RESULTS_ENABLED
+ hub.HOG_INVOCATION_RESULTS_ENABLED = true
+
+ try {
+ const res = await supertest(app)
+ .post(
+ `/api/projects/${scheduleHogFlow.team_id}/hog_flows/${scheduleHogFlow.id}/scheduled_invocations`
+ )
+ .send({})
+
+ expect(res.status).toEqual(200)
+ expect(parseJSON(stateWhenQueued!).firstScheduledAt).toEqual(expect.any(String))
+ } finally {
+ hub.HOG_INVOCATION_RESULTS_ENABLED = resultsEnabled
+ }
+ })
+
+ it('drops the buffered lifecycle row when the invocation cannot be queued', async () => {
+ const resultsEnabled = hub.HOG_INVOCATION_RESULTS_ENABLED
+ hub.HOG_INVOCATION_RESULTS_ENABLED = true
+ const rowsService = api['invocationResultsService'].invocationResultsRowsService
+ const produceSpy = jest.spyOn(rowsService['outputs'], 'produce').mockResolvedValue(undefined as any)
+ mockQueueInvocations.mockRejectedValueOnce(new Error('queue unavailable'))
+
+ try {
+ const res = await supertest(app)
+ .post(
+ `/api/projects/${scheduleHogFlow.team_id}/hog_flows/${scheduleHogFlow.id}/scheduled_invocations`
+ )
+ .send({})
+
+ expect(res.status).toEqual(500)
+
+ // The row outlives the request on the shared service, so a later flush would
+ // publish a run that never entered cyclotron.
+ await rowsService.flush()
+ expect(produceSpy).not.toHaveBeenCalled()
+ } finally {
+ hub.HOG_INVOCATION_RESULTS_ENABLED = resultsEnabled
+ produceSpy.mockRestore()
+ }
+ })
+
it('queues invocation with empty variables when none provided', async () => {
const res = await supertest(app)
.post(`/api/projects/${scheduleHogFlow.team_id}/hog_flows/${scheduleHogFlow.id}/scheduled_invocations`)
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index ddfcaa70559b..dede3b9351bb 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -920,7 +920,19 @@ export class CdpApi {
const invocation = createHogFlowInvocation(triggerGlobals, hogFlow, filterGlobals)
- await this.hogflowQueue.queueInvocations([invocation])
+ // Queued before queueInvocations serializes the invocation, so the
+ // `state.firstScheduledAt` stamp reaches cyclotron.
+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')
+
+ try {
+ await this.hogflowQueue.queueInvocations([invocation])
+ } catch (error) {
+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor([invocation.id])
+ throw error
+ }
+ // Only the lifecycle sink, which swallows its own produce failures. Flushing every sink
+ // would fail an enqueued run on an unrelated sink's error, and the caller would retry it.
+ await this.invocationResultsService.invocationResultsRowsService.flush()
res.json({ status: 'queued', invocation_id: invocation.id })
} catch (e) {
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
index 5bee38308cf9..1a18330da176 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
@@ -14,6 +14,7 @@ import { template as pixelTemplate } from '~/cdp/templates/_sources/pixel/pixel.
import { template as incomingWebhookTemplate } from '~/cdp/templates/_sources/webhook/incoming_webhook.template'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, HogFunctionType } from '~/cdp/types'
import { setupExpressApp } from '~/common/api/router'
+import { KAFKA_HOG_INVOCATION_RESULTS } from '~/common/config/kafka-topics'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
@@ -541,6 +542,57 @@ describe('SourceWebhooksConsumer', () => {
])
})
+ it('records a running row and stamps the run start into the queued state', async () => {
+ // Lifecycle rows are gated on this flag, which is off by default outside dev.
+ hub.HOG_INVOCATION_RESULTS_ENABLED = true
+ let stateWhenQueued: string | undefined
+ // Snapshot at call time, so a stamp applied after queueInvocations does not count.
+ mockQueueHogflowInvocationsSpy.mockImplementation((invocations: any[]) => {
+ stateWhenQueued = JSON.stringify(invocations[0].state)
+ return Promise.resolve()
+ })
+
+ const res = await doPostRequest({
+ webhookId: hogFlow.id,
+ body: {
+ event: 'my-event',
+ distinct_id: 'test-distinct-id',
+ },
+ })
+ expect(res.status).toEqual(201)
+ await waitForBackgroundTasks()
+
+ const rows = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)
+ expect(rows).toHaveLength(1)
+ expect(rows[0].value).toMatchObject({
+ invocation_id: mockQueueHogflowInvocationsSpy.mock.calls[0][0][0].id,
+ team_id: team.id,
+ function_kind: 'hog_flow',
+ function_id: hogFlow.id,
+ status: 'running',
+ })
+
+ expect(parseJSON(stateWhenQueued!).firstScheduledAt).toEqual(rows[0].value.first_scheduled_at)
+ })
+
+ it('records no running row when the workflow cannot be queued', async () => {
+ hub.HOG_INVOCATION_RESULTS_ENABLED = true
+ mockQueueHogflowInvocationsSpy.mockRejectedValueOnce(new Error('queue unavailable'))
+
+ const res = await doPostRequest({
+ webhookId: hogFlow.id,
+ body: {
+ event: 'my-event',
+ distinct_id: 'test-distinct-id',
+ },
+ })
+
+ expect(res.status).toEqual(500)
+ await waitForBackgroundTasks()
+ // A row here would show a run that never entered cyclotron as permanently running.
+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)).toEqual([])
+ })
+
it('does not report a workflow trigger as CDP usage', async () => {
const reportBillableInvocation = jest.spyOn(
api['cdpSourceWebhooksConsumer']['cdpUsageReporter'],
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
index 1683f8f478e3..a9d6a08f8c1b 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
@@ -299,6 +299,14 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
count: 1,
})
+ // Queued before queueInvocations serializes the invocation, because
+ // queueLifecycleRow stamps `state.firstScheduledAt` and only a stamp set before
+ // serialization reaches cyclotron.
+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(
+ hogFlowInvocation,
+ 'running'
+ )
+
await this.hogflowQueue.queueInvocations([hogFlowInvocation])
} else {
addMetric({
@@ -313,6 +321,9 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
return functionResult
} catch (error) {
logger.error('Error triggering hog flow', { error })
+ // The 'running' row is queued before the invocation reaches cyclotron, so a throw after
+ // that point leaves a row for a run that does not exist and would never terminate.
+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor([invocationId])
addMetric({
metric_kind: 'failure',
metric_name: 'trigger_failed',