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.

feat(workflows): expose an in-flight run count for hog flows (#70796)

Harley Alexander5f61d05b45cf
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index c57f7ea30f00..69699825601f 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -15,7 +15,7 @@ import { UUIDT } from '~/common/utils/utils'
import { createCdpConsumerDeps } from '../../tests/helpers/cdp'
import { forSnapshot } from '../../tests/helpers/snapshots'
-import { getFirstTeam, resetTestDatabase } from '../../tests/helpers/sql'
+import { createTeam, getFirstTeam, resetTestDatabase } from '../../tests/helpers/sql'
import { Hub, Team } from '../types'
import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from './_tests/examples'
@@ -914,6 +914,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
+ countInFlightJobs: jest.fn().mockResolvedValue(0),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1000,6 +1001,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
+ countInFlightJobs: jest.fn().mockResolvedValue(0),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1060,6 +1062,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
+ countInFlightJobs: jest.fn().mockResolvedValue(0),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1168,6 +1171,79 @@ describe('CDP API', () => {
})
})
+ describe('hogflow in-flight count', () => {
+ let countHogFlow: HogFlow
+ let mockCountInFlightJobs: jest.Mock
+
+ beforeEach(async () => {
+ mockCountInFlightJobs = jest.fn().mockResolvedValue(3)
+ api['batchResolverProducer'] = {
+ createJob: jest.fn(),
+ disconnect: jest.fn(),
+ countInFlightJobs: mockCountInFlightJobs,
+ }
+
+ countHogFlow = await insertHogFlow({
+ id: new UUIDT().toString(),
+ name: 'test in-flight count hog flow',
+ status: 'active',
+ version: 1,
+ exit_condition: 'exit_on_conversion',
+ edges: [],
+ actions: [],
+ trigger: {
+ type: 'event',
+ filters: {},
+ },
+ })
+ })
+
+ afterEach(() => {
+ api['batchResolverProducer'] = null
+ })
+
+ it('returns the in-flight job count for a workflow', async () => {
+ const res = await supertest(app).get(
+ `/api/projects/${countHogFlow.team_id}/hog_flows/${countHogFlow.id}/in_flight_count`
+ )
+
+ expect(res.status).toEqual(200)
+ expect(res.body).toEqual({ count: 3 })
+ expect(mockCountInFlightJobs).toHaveBeenCalledWith(countHogFlow.team_id, countHogFlow.id)
+ })
+
+ it('errors if missing hog flow', async () => {
+ const res = await supertest(app).get(
+ `/api/projects/${countHogFlow.team_id}/hog_flows/${new UUIDT().toString()}/in_flight_count`
+ )
+
+ expect(res.status).toEqual(404)
+ expect(res.body.error).toEqual('Workflow not found')
+ })
+
+ it("errors when requesting another team's hog flow", async () => {
+ const otherTeamId = await createTeam(hub.postgres, team.organization_id)
+
+ const res = await supertest(app).get(
+ `/api/projects/${otherTeamId}/hog_flows/${countHogFlow.id}/in_flight_count`
+ )
+
+ expect(res.status).toEqual(404)
+ expect(res.body.error).toEqual('Workflow not found')
+ expect(mockCountInFlightJobs).not.toHaveBeenCalled()
+ })
+
+ it('errors if the cyclotron producer is not configured', async () => {
+ api['batchResolverProducer'] = null
+
+ const res = await supertest(app).get(
+ `/api/projects/${countHogFlow.team_id}/hog_flows/${countHogFlow.id}/in_flight_count`
+ )
+
+ expect(res.status).toEqual(503)
+ })
+ })
+
// The test panel POSTs to /hog_flows/:id/invocations and runs the executor in-process —
// it never enqueues into cyclotron. If the executor routes an email action onto the
// dedicated email queue, nothing services that job and the workflow stalls on a
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 16367130f178..291e9c84e648 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -238,6 +238,7 @@ export class CdpApi {
asyncHandler(this.postRerunInvocations('hog_function'))
)
router.post('/api/projects/:team_id/hog_flows/:id/rerun', asyncHandler(this.postRerunInvocations('hog_flow')))
+ router.get('/api/projects/:team_id/hog_flows/:id/in_flight_count', asyncHandler(this.getHogFlowInFlightCount))
router.get('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.getFunctionStatus()))
router.patch('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.patchFunctionStatus()))
router.get('/api/hog_functions/states', asyncHandler(this.getFunctionStates()))
@@ -799,6 +800,37 @@ export class CdpApi {
}
}
+ // How many of this workflow's runs are still in flight (parked on waits/delays or actively
+ // executing). Django calls this to show publish/edit impact before a live workflow changes.
+ private getHogFlowInFlightCount = async (req: ModifiedRequest, res: express.Response): Promise<any> => {
+ try {
+ if (!this.batchResolverProducer) {
+ return res.status(503).json({
+ error: 'Cyclotron producer not initialized (CYCLOTRON_NODE_DATABASE_URL unset)',
+ })
+ }
+
+ const { team_id, id } = req.params
+ const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)
+ if (!team) {
+ return res.status(404).json({ error: 'Team not found' })
+ }
+
+ const hogFlow = await this.hogFlowManager.getHogFlow(id)
+ if (!hogFlow || hogFlow.team_id !== team.id) {
+ return res.status(404).json({ error: 'Workflow not found' })
+ }
+
+ const count = await this.batchResolverProducer.countInFlightJobs(team.id, id)
+ return res.json({ count })
+ } catch (e) {
+ logger.error('Error counting in-flight hog flow jobs', {
+ error: e instanceof Error ? e.message : String(e),
+ })
+ return res.status(500).json({ error: e instanceof Error ? e.message : String(e) })
+ }
+ }
+
private postHogFlowBatchInvocation = async (req: ModifiedRequest, res: express.Response): Promise<any> => {
try {
const { id, team_id, parent_run_id } = req.params
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 c9effbffa469..17d9f0086046 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -254,6 +254,21 @@ describe('Cyclotron V2', () => {
}
)
+ it('countInFlightJobs counts available and running jobs for one team and function', async () => {
+ const functionId = uuidv7()
+ const otherFunctionId = uuidv7()
+ await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
+ const runningId = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'running' WHERE id = $1`, [runningId])
+ // Not counted: terminal status, other function, other team
+ const completedId = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'completed' WHERE id = $1`, [completedId])
+ await manager.createJob({ teamId: 1, queueName: QUEUE, functionId: otherFunctionId })
+ await manager.createJob({ teamId: 2, queueName: QUEUE, functionId })
+
+ expect(await manager.countInFlightJobs(1, functionId)).toBe(2)
+ })
+
it('backpressure throws when queue depth exceeds limit', async () => {
const smallManager = createManager({ depthLimit: 2, depthCheckIntervalMs: 0 })
await smallManager.connect()
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 2d5a5d1c817f..72f881b3dfb9 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -391,6 +391,17 @@ export class CyclotronV2Manager {
return dequeueSeqs
}
+ // "In flight" = jobs still owned by the queue: parked waits/delays ('available' with a future
+ // scheduled time) and jobs a worker currently holds ('running'). Terminal rows don't count.
+ async countInFlightJobs(teamId: number, functionId: string): Promise<number> {
+ const result = await this.pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count FROM cyclotron_jobs
+ WHERE team_id = $1 AND function_id = $2 AND status IN ('available', 'running')`,
+ [teamId, functionId]
+ )
+ return result.rows[0].count
+ }
+
async disconnect(): Promise<void> {
await this.pool.end()
}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index 4d7cd9498de3..e95495bc7997 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -101,6 +101,7 @@ export type CyclotronV2ManagerConfig = {
*/
export interface CyclotronV2JobProducer {
createJob(input: CyclotronV2JobInit): Promise<string>
+ countInFlightJobs(teamId: number, functionId: string): Promise<number>
disconnect(): Promise<void>
}
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index eb4fc7912a27..05fc9b2ac5b5 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -107,6 +107,13 @@ def create_hog_flow_scheduled_invocation(
)
+def get_hog_flow_in_flight_count(team_id: int, hog_flow_id: str) -> requests.Response:
+ return internal_requests.get(
+ CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/in_flight_count",
+ headers=get_internal_api_headers(),
+ )
+
+
def get_hog_function_status(team_id: int, hog_function_id: UUIDT) -> requests.Response:
return internal_requests.get(
CDP_API_URL + f"/api/projects/{team_id}/hog_functions/{hog_function_id}/status",