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): cancel in-flight workflow runs (#83342)

Harley Alexander5a67b89b4724
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 32cdab80c71a..5bef6f5caf13 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7033,9 +7033,9 @@ snapshots:
scenes-app-notebooks-widget-views--survey-views--light:
hash: v1.k794b7964.3dad7f9ff2bafb766aae416a754bb9830773e886993739e75339d6dc75d668d0.PlGQ57dwA4jzdVj-lXAcqVCY0YxNXkT0w0ZZrvYmI0Y
scenes-app-notebooks-widget-views--workflow-views--dark:
- hash: v1.k794b7964.9f9da8402d368380cb5e5c369dfbfe271d10dca4b7da10ecb4c985f581d32580.X0UX9PxrvIZcRPxQ9Bi0c9qJVRqQ3GCGMHR8ubsB9KE
+ hash: v1.k794b7964.6c3b6ef52b19223903911867b010844352f5b4883d92766cf163f4db558b8419.ZjLDs3scIHzDzzSGNQ8eFZe3n4pHXvxzJ0VhDjJmnxQ
scenes-app-notebooks-widget-views--workflow-views--light:
- hash: v1.k794b7964.8539569f6f314d8c6f7847f9791392edcb1d48345e37b231672f4b36bc579b3c.VlcXGpaH6yQ9ltXVpnnHUmQEHAY0k5k-UQLJ9fZ3cUk
+ hash: v1.k794b7964.064edb23945005b5c823d536379fd2452ec6869b4261b3fad548d7a2ee60ee35.ri6wAnXDlZHcjYG-JjdKjkFiSRtHzZq_XwQQ4hvqthY
scenes-app-oauth-authorize--all-scopes-optional--dark:
hash: v1.k794b7964.03746d2e3646b97e4af61e54557db2ccb6268512cda02721b819fa30980af155.ZPcclnqMQQh8Qi_v2Z3cnVA1_LaYFx8XXncRQ8NQAdc
scenes-app-oauth-authorize--all-scopes-optional--light:
diff --git a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
index 8d2ab593ba85..50afab0e2b46 100644
--- a/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/HogInvocations.tsx
@@ -58,6 +58,7 @@ const STATUS_OPTIONS: { value: RunStatus; label: string }[] = [
{ value: 'running', label: 'Running' },
{ value: 'succeeded', label: 'Succeeded' },
{ value: 'failed', label: 'Failed' },
+ { value: 'canceled', label: 'Canceled' },
]
/**
@@ -118,6 +119,8 @@ const tagTypeForStatus = (status: RunStatus): LemonTagProps['type'] => {
return 'success'
case 'failed':
return 'danger'
+ case 'canceled':
+ return 'muted'
case 'running':
default:
return 'warning'
@@ -265,6 +268,8 @@ export function HogInvocations({
personPropertiesById,
sparkline,
sparklineLoading,
+ cancellingInvocationIds,
+ cancellingAll,
} = useValues(logic)
const {
loadMore,
@@ -275,6 +280,8 @@ export function HogInvocations({
setSelectedIds,
setExpanded,
rerunInvocations,
+ cancelInvocations,
+ cancelAllInvocations,
bulkRerun,
} = useActions(logic)
const [rerunModalOpen, setRerunModalOpen] = useState(false)
@@ -471,6 +478,37 @@ export function HogInvocations({
if (isRerunWrapperKind(row.function_kind)) {
return null
}
+ // Cancel is workflows-only: a workflow run in flight is usually parked on a delay
+ // or wait that an operator may need to stop, while a hog function run completes in
+ // seconds, so its in-flight rows keep the disabled Rerun instead.
+ if (functionKind === 'hog_flow' && row.status === 'running') {
+ return (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ status="danger"
+ loading={cancellingInvocationIds.includes(row.invocation_id)}
+ onClick={() => {
+ LemonDialog.open({
+ title: 'Cancel this run?',
+ // Two sentences of copy; the default dialog width spans the screen.
+ maxWidth: '30rem',
+ content:
+ 'The run stops before its next step. Steps that already ran, ' +
+ 'like sent emails, are not undone.',
+ primaryButton: {
+ children: 'Cancel run',
+ status: 'danger',
+ onClick: () => cancelInvocations([row.invocation_id]),
+ },
+ secondaryButton: { children: 'Keep running' },
+ })
+ }}
+ >
+ Cancel
+ </LemonButton>
+ )
+ }
return (
<LemonButton
size="xsmall"
@@ -588,6 +626,35 @@ export function HogInvocations({
>
Refresh
</LemonButton>
+ {/* Workflow-wide cancel. Hidden in a parent-run-scoped or compact view, where
+ its whole-workflow scope would read as scoped to the visible subset. */}
+ {functionKind === 'hog_flow' && !compact && !parentRunId ? (
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconX />}
+ loading={cancellingAll}
+ onClick={() => {
+ LemonDialog.open({
+ title: 'Cancel all in-flight runs?',
+ maxWidth: '30rem',
+ content:
+ 'Every run of this workflow that has not finished stops before its ' +
+ 'next step, including runs parked on delays and waits. Steps that ' +
+ 'already ran, like sent emails, are not undone.',
+ primaryButton: {
+ children: 'Cancel all runs',
+ status: 'danger',
+ onClick: () => cancelAllInvocations(),
+ },
+ secondaryButton: { children: 'Keep running' },
+ })
+ }}
+ >
+ Cancel in-flight runs
+ </LemonButton>
+ ) : null}
{compact ? null : (
<LemonButton
size="small"
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
index 6e8058dbd693..c63b4abef072 100644
--- a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
@@ -15,7 +15,7 @@ import { HogFunctionTypeType, LogEntryLevel, PersonType } from '~/types'
import { hogFunctionsRerunCreate } from 'products/cdp/frontend/generated/api'
import type { HogInvocationRerunFilterStatusEnumApi } from 'products/cdp/frontend/generated/api.schemas'
-import { hogFlowsRerunCreate } from 'products/workflows/frontend/generated/api'
+import { hogFlowsInvocationsCancelCreate, hogFlowsRerunCreate } from 'products/workflows/frontend/generated/api'
export const HOG_INVOCATIONS_PAGE_SIZE = 100
@@ -23,7 +23,7 @@ export const HOG_INVOCATIONS_PAGE_SIZE = 100
* `HOG_INVOCATION_RERUN_MAX_COUNT` env var (Django serializer + Node CDP config). */
export const HOG_INVOCATIONS_RERUN_MAX_COUNT = 10000
-export type RunStatus = 'running' | 'succeeded' | 'failed'
+export type RunStatus = 'running' | 'succeeded' | 'failed' | 'canceled'
export type HogInvocationsFunctionKind = 'hog_function' | 'hog_flow'
@@ -180,7 +180,9 @@ const searchParamsToFilters = (searchParams: Record<string, string | undefined>)
}
const status = searchParams[URL_PARAMS.status]
if (status) {
- next.status = status.split(',').filter((s): s is RunStatus => ['running', 'succeeded', 'failed'].includes(s))
+ next.status = status
+ .split(',')
+ .filter((s): s is RunStatus => ['running', 'succeeded', 'failed', 'canceled'].includes(s))
}
const errorKind = searchParams[URL_PARAMS.error_kind]
if (errorKind) {
@@ -543,6 +545,7 @@ const SPARKLINE_STATUS_COLORS: Record<RunStatus, string> = {
running: 'warning',
succeeded: 'success',
failed: 'danger',
+ canceled: 'muted',
}
async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvocationsFilters): Promise<SparklineData> {
@@ -619,7 +622,7 @@ async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvoc
if (!key) {
continue
}
- const cell = (cellsByBucket[key] = cellsByBucket[key] ?? { running: 0, succeeded: 0, failed: 0 })
+ const cell = (cellsByBucket[key] = cellsByBucket[key] ?? { running: 0, succeeded: 0, failed: 0, canceled: 0 })
cell[status] = (cell[status] ?? 0) + Number(n ?? 0)
}
// Walk every bucket in the filter range — not just the ones CH returned
@@ -629,7 +632,7 @@ async function fetchSparkline(props: HogInvocationsLogicProps, filters: HogInvoc
const timezone = teamTimezone()
const dates = buckets.map((key) => dayjs.tz(key, timezone).toISOString())
const buildValues = (status: RunStatus): number[] => buckets.map((key) => cellsByBucket[key]?.[status] ?? 0)
- const series: SparklineSeries[] = (['failed', 'running', 'succeeded'] as RunStatus[]).map((status) => ({
+ const series: SparklineSeries[] = (['failed', 'running', 'succeeded', 'canceled'] as RunStatus[]).map((status) => ({
name: status,
color: SPARKLINE_STATUS_COLORS[status],
values: buildValues(status),
@@ -826,6 +829,8 @@ async function fetchProblemLevels(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogInvocationsLogicValues {
canBulkRerun: boolean
+ cancellingAll: boolean
+ cancellingInvocationIds: string[]
expandedIds: Record<string, boolean>
filters: HogInvocationsFilters
hasLoadedOnce: boolean
@@ -859,6 +864,18 @@ export interface hogInvocationsLogicActions {
bulkRerun: (params: BulkRerunParams) => {
params: BulkRerunParams
}
+ cancelAllInvocations: () => {
+ value: true
+ }
+ cancelAllInvocationsComplete: () => {
+ value: true
+ }
+ cancelInvocations: (invocationIds: string[]) => {
+ invocationIds: string[]
+ }
+ cancelInvocationsComplete: (invocationIds: string[]) => {
+ invocationIds: string[]
+ }
clearSelected: () => {
value: true
}
@@ -1049,6 +1066,10 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
hydratePeople: (personIds: string[]) => ({ personIds }),
setExpanded: (invocationId: string, expanded: boolean) => ({ invocationId, expanded }),
rerunInvocations: (invocationIds: string[]) => ({ invocationIds }),
+ cancelInvocations: (invocationIds: string[]) => ({ invocationIds }),
+ cancelInvocationsComplete: (invocationIds: string[]) => ({ invocationIds }),
+ cancelAllInvocations: true,
+ cancelAllInvocationsComplete: true,
bulkRerun: (params: BulkRerunParams) => ({ params }),
setHasMore: (hasMore: boolean) => ({ hasMore }),
// Person filter picker: user picks a person from the typeahead → chip stays in the
@@ -1126,6 +1147,26 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
resetFilters: () => null,
},
],
+ // Guard the Cancel buttons against a second request while the first is in flight: a run
+ // stays 'running' until the worker terminates it and the reload lands, so the trigger
+ // stays clickable. Track per invocation id and clear when the request settles.
+ cancellingInvocationIds: [
+ [] as string[],
+ {
+ cancelInvocations: (state: string[], { invocationIds }: { invocationIds: string[] }) => [
+ ...new Set([...state, ...invocationIds]),
+ ],
+ cancelInvocationsComplete: (state: string[], { invocationIds }: { invocationIds: string[] }) =>
+ state.filter((id) => !invocationIds.includes(id)),
+ },
+ ],
+ cancellingAll: [
+ false,
+ {
+ cancelAllInvocations: () => true,
+ cancelAllInvocationsComplete: () => false,
+ },
+ ],
}
}),
@@ -1264,7 +1305,7 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
statusCounts: [
(s) => [s.runs],
(runs: HogInvocationRow[]): Record<RunStatus, number> => {
- const counts: Record<RunStatus, number> = { running: 0, succeeded: 0, failed: 0 }
+ const counts: Record<RunStatus, number> = { running: 0, succeeded: 0, failed: 0, canceled: 0 }
for (const r of runs) {
counts[r.status] = (counts[r.status] ?? 0) + 1
}
@@ -1400,7 +1441,7 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
// defaults a missing status to ['failed'], which would silently drop
// succeeded rows the user explicitly selected. The ID restriction
// alone determines what gets rerun (the worker still skips in-flight).
- status: ['running', 'succeeded', 'failed'] as HogInvocationRerunFilterStatusEnumApi[],
+ status: ['running', 'succeeded', 'failed', 'canceled'] as HogInvocationRerunFilterStatusEnumApi[],
},
}
@@ -1420,6 +1461,68 @@ export const hogInvocationsLogic = kea<hogInvocationsLogicType>([
lemonToast.error(`Failed to enqueue rerun: ${e?.detail ?? e?.message ?? String(e)}`)
}
},
+ cancelInvocations: async ({ invocationIds }) => {
+ if (props.functionKind !== 'hog_flow' || invocationIds.length === 0) {
+ actions.cancelInvocationsComplete(invocationIds)
+ return
+ }
+
+ const teamId = ApiConfig.getCurrentTeamId()
+ try {
+ const response = await hogFlowsInvocationsCancelCreate(String(teamId), props.id, {
+ invocation_ids: invocationIds,
+ })
+ const marked = response.marked ?? 0
+ if (marked > 0) {
+ lemonToast.success(
+ `Cancellation requested for ${marked} ${marked === 1 ? 'run' : 'runs'}. Parked runs stop within moments. Runs mid-step stop at their next step.`
+ )
+ } else {
+ lemonToast.info('Nothing to cancel. The runs may have finished or are already being canceled.')
+ }
+ // Canceled rows flip once the worker terminates them, so poll briefly and the
+ // status change surfaces without a manual refresh.
+ cache.forceRefreshUntil = Date.now() + FORCE_REFRESH_WINDOW_MS
+ actions.loadRuns(null)
+ } catch (e: any) {
+ lemonToast.error(`Failed to cancel: ${e?.detail ?? e?.message ?? String(e)}`)
+ } finally {
+ actions.cancelInvocationsComplete(invocationIds)
+ }
+ },
+ cancelAllInvocations: async () => {
+ if (props.functionKind !== 'hog_flow') {
+ actions.cancelAllInvocationsComplete()
+ return
+ }
+
+ const teamId = ApiConfig.getCurrentTeamId()
+ try {
+ const response = await hogFlowsInvocationsCancelCreate(String(teamId), props.id, { all: true })
+ const marked = response.marked ?? 0
+ if (!response.done) {
+ // One request sweeps a bounded batch of runs, so a very large or still-enrolling
+ // workflow leaves some unflagged. Prompt another pass instead of reporting a clean stop.
+ lemonToast.warning(
+ `Cancellation requested for ${marked} ${marked === 1 ? 'run' : 'runs'}, but more are still in flight. Run "Cancel in-flight runs" again to catch the rest.`
+ )
+ } else if (marked > 0) {
+ lemonToast.success(
+ `Cancellation requested for ${marked} in-flight ${marked === 1 ? 'run' : 'runs'}. Parked runs stop within moments. Runs mid-step stop at their next step.`
+ )
+ } else {
+ lemonToast.info('No runs are in flight for this workflow.')
+ }
+ // Canceled rows flip once the worker terminates them, so poll briefly and the
+ // status change surfaces without a manual refresh.
+ cache.forceRefreshUntil = Date.now() + FORCE_REFRESH_WINDOW_MS
+ actions.loadRuns(null)
+ } catch (e: any) {
+ lemonToast.error(`Failed to cancel: ${e?.detail ?? e?.message ?? String(e)}`)
+ } finally {
+ actions.cancelAllInvocationsComplete()
+ }
+ },
bulkRerun: async ({ params }) => {
const teamId = ApiConfig.getCurrentTeamId()
// Resolve via `resolveDateRange` so `-24h` produces "24 hours ago",
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index 7745d9e1e012..43f9cd2a861e 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -1180,6 +1180,7 @@ describe('CDP API', () => {
createJob: createJobMock,
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1238,6 +1239,7 @@ describe('CDP API', () => {
createJob: createJobMock,
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1298,6 +1300,7 @@ describe('CDP API', () => {
createJob: createJobMock,
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1360,6 +1363,7 @@ describe('CDP API', () => {
createJob: createJobMock,
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1481,6 +1485,7 @@ describe('CDP API', () => {
disconnect: jest.fn(),
countInFlightJobs: mockCountInFlightJobs,
rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
}
countHogFlow = await insertHogFlow({
@@ -1573,6 +1578,7 @@ describe('CDP API', () => {
disconnect: jest.fn(),
countInFlightJobs: jest.fn(),
rescheduleParkedJobs: mockRescheduleParkedJobs,
+ cancelJobs: jest.fn(),
}
rescheduleHogFlow = await insertHogFlow({
@@ -1723,6 +1729,102 @@ describe('CDP API', () => {
})
})
+ describe('hogflow cancel invocations auth', () => {
+ let mockCancelJobs: jest.Mock
+
+ // Built with the raw audience literal and Python claim names: this is the wire contract
+ // with Django's WORKFLOWS_CANCEL_INVOCATIONS_JWT_PURPOSE, so drift on either side breaks here.
+ const mintCancelToken = (
+ teamId: number,
+ hogFlowId: string,
+ { secret = 'local-dev-workflows-reschedule-jwt', audience = 'posthog:workflows:cancel_invocations' } = {}
+ ) => jwt.sign({ team_id: teamId, hog_flow_id: hogFlowId }, secret, { audience, expiresIn: '2m' })
+
+ // No hog flow row exists for this id: cancel deliberately skips the flow lookup so it
+ // keeps working for flows deleted with runs still parked.
+ const cancelFlowId = new UUIDT().toString()
+ const cancelAuth = (teamId: number, hogFlowId: string) => ({
+ Authorization: `Bearer ${mintCancelToken(teamId, hogFlowId)}`,
+ })
+
+ beforeEach(() => {
+ mockCancelJobs = jest.fn().mockResolvedValue({ marked: 3, remaining: 0, done: true })
+ api['batchResolverProducer'] = {
+ createJob: jest.fn(),
+ disconnect: jest.fn(),
+ countInFlightJobs: jest.fn(),
+ rescheduleParkedJobs: jest.fn(),
+ cancelJobs: mockCancelJobs,
+ }
+ })
+
+ afterEach(() => {
+ api['batchResolverProducer'] = null
+ })
+
+ it('accepts a Django-minted token and marks the flagged jobs', async () => {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${cancelFlowId}/invocations/cancel`)
+ .set(cancelAuth(team.id, cancelFlowId))
+ .send({ all: true })
+
+ expect(res.status).toEqual(200)
+ expect(res.body).toEqual({ marked: 3, remaining: 0, done: true })
+ expect(mockCancelJobs).toHaveBeenCalledWith(
+ expect.objectContaining({ teamId: team.id, functionId: cancelFlowId, all: true })
+ )
+ })
+
+ it.each([
+ ['no token', () => ({})],
+ [
+ 'a token signed with the wrong key',
+ () => ({
+ Authorization: `Bearer ${mintCancelToken(team.id, cancelFlowId, { secret: 'wrong-key' })}`,
+ }),
+ ],
+ [
+ "another workflow's token",
+ () => ({ Authorization: `Bearer ${mintCancelToken(team.id, new UUIDT().toString())}` }),
+ ],
+ ["another team's token", () => ({ Authorization: `Bearer ${mintCancelToken(team.id + 1, cancelFlowId)}` })],
+ [
+ // The cancel purpose shares its signing key with reschedule_parked, so the audience
+ // is the only thing keeping a reschedule token out of cancel.
+ 'a reschedule-audience token',
+ () => ({
+ Authorization: `Bearer ${mintCancelToken(team.id, cancelFlowId, {
+ audience: 'posthog:workflows:reschedule_parked',
+ })}`,
+ }),
+ ],
+ ])('rejects a request with %s', async (_desc, headers) => {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${cancelFlowId}/invocations/cancel`)
+ .set(headers())
+ .send({ all: true })
+
+ expect(res.status).toEqual(401)
+ expect(mockCancelJobs).not.toHaveBeenCalled()
+ })
+
+ it('fails closed when the cancel JWT key is not provisioned', async () => {
+ const savedJwt = api['cancelInvocationsJwt']
+ api['cancelInvocationsJwt'] = new ScopedServiceJwt(PosthogJwtAudience.WORKFLOWS_CANCEL_INVOCATIONS, '')
+ try {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/hog_flows/${cancelFlowId}/invocations/cancel`)
+ .set(cancelAuth(team.id, cancelFlowId))
+ .send({ all: true })
+
+ expect(res.status).toEqual(503)
+ expect(mockCancelJobs).not.toHaveBeenCalled()
+ } finally {
+ api['cancelInvocationsJwt'] = savedJwt
+ }
+ })
+ })
+
// 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 489f78e02dc6..0690136eb78b 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -1,5 +1,6 @@
import { DateTime } from 'luxon'
import express from 'ultimate-express'
+import { z } from 'zod'
import { ModifiedRequest } from '~/common/api/router'
import { logger } from '~/common/utils/logger'
@@ -144,10 +145,11 @@ export class CdpApi {
private batchExportHogFunctionService: BatchExportHogFunctionService
private groupsManager: GroupsManagerService
private batchResolverProducer: CyclotronV2JobProducer | null
- // Scoped auth for the reschedule_parked route (exempted from the shared internal-secret
- // middleware): Django mints per-call JWTs pinned to a team + workflow. Disabled when the key
- // isn't provisioned — the route then fails closed.
+ // Scoped auth for the reschedule_parked and invocations/cancel routes (exempted from the
+ // shared internal-secret middleware): Django mints per-call JWTs pinned to a team + workflow,
+ // one audience per route. Disabled when the key isn't provisioned — the routes then fail closed.
private rescheduleJwt: ScopedServiceJwt
+ private cancelInvocationsJwt: ScopedServiceJwt
constructor(
private config: PluginsServerConfig,
@@ -203,6 +205,10 @@ export class CdpApi {
PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED,
config.WORKFLOWS_RESCHEDULE_JWT_SECRET || ''
)
+ this.cancelInvocationsJwt = new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOWS_CANCEL_INVOCATIONS,
+ config.WORKFLOWS_RESCHEDULE_JWT_SECRET || ''
+ )
}
public get service(): PluginServerService {
@@ -274,6 +280,10 @@ export class CdpApi {
'/api/projects/:team_id/hog_flows/:id/reschedule_parked',
asyncHandler(this.postHogFlowRescheduleParked)
)
+ router.post(
+ '/api/projects/:team_id/hog_flows/:id/invocations/cancel',
+ asyncHandler(this.postHogFlowCancelInvocations)
+ )
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()))
@@ -1022,6 +1032,32 @@ export class CdpApi {
}
}
+ // Shared gate for the per-call scoped JWTs Django mints (reschedule, cancel): verifies the
+ // token and requires its claims to match the URL's team + workflow, so a leaked token can't
+ // touch another team or flow. Writes the 401 itself and returns false on any mismatch.
+ private verifyScopedWorkflowJwt(
+ jwt: ScopedServiceJwt,
+ req: ModifiedRequest,
+ res: express.Response,
+ label: string
+ ): boolean {
+ const { team_id, id } = req.params
+ const authHeader = req.headers['authorization']
+ const token =
+ typeof authHeader === 'string' && authHeader.startsWith('Bearer ') ? authHeader.slice(7) : undefined
+ let claims: { team_id?: number; hog_flow_id?: string } | undefined
+ try {
+ claims = token ? (jwt.verify(token) as typeof claims) : undefined
+ } catch {
+ claims = undefined
+ }
+ if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id) {
+ res.status(401).json({ error: `Unauthorized: Invalid ${label} token` })
+ return false
+ }
+ return true
+ }
+
// Pull forward the wake times of this workflow's parked jobs after a timing edit. Django
// calls this (via a Celery task) when a published/saved change shortened a delay or moved a
// wait window; one call is one slice, and the caller loops with the returned bounds until
@@ -1045,18 +1081,8 @@ export class CdpApi {
const { team_id, id } = req.params
- const authHeader = req.headers['authorization']
- const token =
- typeof authHeader === 'string' && authHeader.startsWith('Bearer ') ? authHeader.slice(7) : undefined
- let claims: { team_id?: number; hog_flow_id?: string } | undefined
- try {
- claims = token ? (this.rescheduleJwt.verify(token) as typeof claims) : undefined
- } catch {
- claims = undefined
- }
- // The claims pin the token to one team + workflow, so a leaked token can't sweep anything else.
- if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id) {
- return res.status(401).json({ error: 'Unauthorized: Invalid reschedule token' })
+ if (!this.verifyScopedWorkflowJwt(this.rescheduleJwt, req, res, 'reschedule')) {
+ return
}
const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)
@@ -1115,6 +1141,88 @@ export class CdpApi {
}
}
+ // Flag a workflow's in-flight cyclotron jobs for cancellation. The workers own the actual
+ // termination (terminal status + lifecycle row + metric + log) when they observe the flag;
+ // this endpoint only marks rows and wakes parked ones. See CyclotronV2Manager.cancelJobs.
+ //
+ // Auth mirrors postHogFlowRescheduleParked: a per-call JWT minted by Django, pinned to this
+ // team + workflow, on its own audience, never the fleet-wide internal secret.
+ private postHogFlowCancelInvocations = 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)',
+ })
+ }
+ if (!this.cancelInvocationsJwt.enabled) {
+ return res.status(503).json({
+ error: 'Workflows scoped auth not configured (WORKFLOWS_RESCHEDULE_JWT_SECRET unset)',
+ })
+ }
+
+ const { team_id, id } = req.params
+
+ if (!this.verifyScopedWorkflowJwt(this.cancelInvocationsJwt, req, res, 'cancel')) {
+ return
+ }
+
+ const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)
+ if (!team) {
+ return res.status(404).json({ error: 'Team not found' })
+ }
+
+ // Deliberately no hogFlowManager lookup beyond team pinning: cancel must keep working
+ // for flows that were deleted with runs still parked. The JWT claims already bind the
+ // request to this flow id, and cancelJobs filters on (team_id, function_id).
+
+ // UUID-shaped ids only: cancelJobs binds them as ::uuid[], so a malformed id must be a
+ // 400 here rather than a Postgres cast error surfaced as a 500. The cap is the same
+ // env-driven one the Django cancel serializer validates against, so raising the env
+ // var lifts both sides together instead of leaving Django accepting ids this route
+ // then rejects with a 400 (which Django surfaces as a 500).
+ const maxInvocationIds = this.config.HOG_INVOCATION_RERUN_MAX_COUNT
+ const idsMessage = `invocation_ids must be a non-empty array of up to ${maxInvocationIds} invocation UUIDs`
+ const parsed = z
+ .object({
+ invocation_ids: z
+ .array(z.string().uuid(idsMessage))
+ .min(1, idsMessage)
+ .max(maxInvocationIds, idsMessage)
+ .optional(),
+ all: z.boolean().optional(),
+ })
+ .refine((body) => (body.invocation_ids !== undefined) !== (body.all === true), {
+ message: 'Provide exactly one of invocation_ids or all=true',
+ })
+ .safeParse(req.body ?? {})
+ if (!parsed.success) {
+ return res.status(400).json({ error: parsed.error.issues[0]?.message ?? 'Invalid request body' })
+ }
+ const { invocation_ids: invocationIds, all } = parsed.data
+
+ const result = await this.batchResolverProducer.cancelJobs({
+ teamId: team.id,
+ functionId: id,
+ jobIds: invocationIds,
+ all: all === true ? true : undefined,
+ // Batch-resolver jobs orchestrate audience fan-out rather than being runs;
+ // flagging one would silently stall a batch with no terminal reporting.
+ // Stopping a batch run is its own feature with its own endpoint.
+ excludeQueueNames: [HOGFLOW_BATCH_RESOLVE_QUEUE],
+ })
+ return res.json({
+ marked: result.marked,
+ remaining: result.remaining,
+ done: result.done,
+ })
+ } catch (e) {
+ logger.error('Error cancelling hog flow invocations', {
+ 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/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
index 972ad461646d..9748bd1c341f 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
@@ -1,3 +1,6 @@
+import { DateTime } from 'luxon'
+
+import { HogFlow } from '~/cdp/schema/hogflow'
import { instrumented } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { PluginsServerConfig } from '~/types'
@@ -5,9 +8,15 @@ import { PluginsServerConfig } from '~/types'
import { JobQueue } from '../services/job-queue/job-queue.interface'
import { CyclotronJobInvocation, CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '../types'
import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
+import { createInvocationResult } from '../utils/invocation-utils'
import { CdpConsumerBaseDeps } from './cdp-base.consumer'
import { CdpCyclotronWorker } from './cdp-cyclotron-worker.consumer'
+type LoadHogFlowsResult = {
+ loadedInvocations: CyclotronJobInvocationHogFlow[]
+ canceledResults: CyclotronJobInvocationResult[]
+}
+
export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
protected override name = 'CdpCyclotronWorkerHogFlow'
@@ -19,18 +28,63 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
public override async processInvocations(
invocations: CyclotronJobInvocation[]
): Promise<CyclotronJobInvocationResult[]> {
- const loadedInvocations = await this.loadHogFlows(invocations)
- return await Promise.all(loadedInvocations.map((item) => this.hogFlowExecutor.execute(item)))
+ const { loadedInvocations, canceledResults } = await this.loadHogFlows(invocations)
+ const executed = await Promise.all(loadedInvocations.map((item) => this.hogFlowExecutor.execute(item)))
+ return [...canceledResults, ...executed]
+ }
+
+ /**
+ * Terminate an invocation as canceled through the normal result pipeline, so the
+ * terminal lifecycle row, app metric, and run log all land. A bare cyclotron
+ * status flip would leave the run showing 'running' in the Invocations UI forever.
+ */
+ private buildCanceledResult(
+ item: CyclotronJobInvocation,
+ message: string,
+ hogFlow?: HogFlow
+ ): CyclotronJobInvocationResult {
+ // The monitoring services identify a workflow result by the presence of `hogFlow`, and use
+ // it to key the terminal lifecycle row as `hog_flow` and to fill the row's trigger fields.
+ // Without it the row keys as `hog_function`; because `function_kind` is part of the
+ // ReplacingMergeTree key, that row could never collapse the `running` row (written as
+ // `hog_flow`), leaving the run stuck at 'running' in the Invocations tab. When the live flow
+ // is gone (deleted, or its lookup failed) we still know its id, which is `item.functionId`,
+ // so attach a minimal stub carrying just that so the row still keys as `hog_flow`. Only `id`
+ // is read off this object on the cancellation path.
+ const resolvedFlow = hogFlow ?? ({ id: item.functionId } as HogFlow)
+ const invocation = { ...item, hogFlow: resolvedFlow }
+ const result = createInvocationResult(invocation, {}, { finished: true })
+ result.canceled = true
+ result.logs.push({ level: 'info', timestamp: DateTime.now(), message })
+ result.metrics.push({
+ team_id: item.teamId,
+ app_source_id: item.parentRunId ?? item.functionId,
+ instance_id: (item.state as CyclotronJobInvocationHogFlow['state'] | null)?.currentAction?.id,
+ metric_kind: 'other',
+ metric_name: 'canceled',
+ count: 1,
+ })
+ return result
}
@instrumented('cdpConsumer.handleEachBatch.loadHogFlows')
- protected async loadHogFlows(invocations: CyclotronJobInvocation[]): Promise<CyclotronJobInvocationHogFlow[]> {
+ protected async loadHogFlows(invocations: CyclotronJobInvocation[]): Promise<LoadHogFlowsResult> {
const loadedInvocations: CyclotronJobInvocationHogFlow[] = []
const failedInvocations: CyclotronJobInvocation[] = []
- const skippedInvocations: CyclotronJobInvocation[] = []
+ const canceledResults: CyclotronJobInvocationResult[] = []
await Promise.all(
invocations.map(async (item) => {
+ // Checked before the team/flow lookups so a cancel-requested run terminates even
+ // when its flow or team has since been deleted. The flow lookup here is
+ // best-effort and only sets the terminal row's function_kind: a null flow
+ // (deleted) or a lookup error still cancels.
+ if (item.cancelRequestedAt) {
+ const hogFlow = await this.hogFlowManager.getHogFlow(item.functionId).catch(() => null)
+ canceledResults.push(this.buildCanceledResult(item, 'Run canceled', hogFlow ?? undefined))
+ return
+ }
+
const team = await this.deps.teamManager.getTeam(item.teamId)
const hogFlow = await this.hogFlowManager.getHogFlow(item.functionId)
if (!hogFlow || !team) {
@@ -43,14 +97,18 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
return
}
- // Skip execution if the workflow is no longer active (e.g., disabled/archived)
+ // A run waking while its workflow is disabled/archived is canceled rather
+ // than executed. Runs that wake while the workflow is active proceed
+ // normally, so re-enabling before a parked run's wake time releases it.
if (hogFlow.status !== 'active') {
- logger.info('⏭️', 'Skipping hog flow invocation - workflow is no longer active', {
+ logger.info('⏭️', 'Cancelling hog flow invocation - workflow is no longer active', {
id: item.functionId,
status: hogFlow.status,
})
- skippedInvocations.push(item)
+ canceledResults.push(
+ this.buildCanceledResult(item, 'Run canceled: the workflow is no longer active', hogFlow)
+ )
return
}
@@ -146,8 +204,7 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
)
await this.cyclotronJobQueue.dequeueInvocations(failedInvocations)
- await this.cyclotronJobQueue.cancelInvocations(skippedInvocations)
- return loadedInvocations
+ return { loadedInvocations, canceledResults }
}
}
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
index 9c75d4ece93f..ac8904d5d5c9 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
@@ -370,7 +370,7 @@ describe('CdpCyclotronWorkerHogFlow', () => {
expect(results[3].invocation.state.personId).toBeUndefined()
})
- it('should skip invocations when workflow is disabled after being queued', async () => {
+ it('terminates invocations as canceled when the workflow is disabled after being queued', async () => {
const hogFlow = hogFlows[0]
const invocation1 = createSerializedHogFlowInvocation(hogFlow, {
@@ -406,19 +406,69 @@ describe('CdpCyclotronWorkerHogFlow', () => {
// Mark the hogflow for refresh so it fetches fresh data
;(processor['hogFlowManager'] as any)['lazyLoader'].markForRefresh(hogFlow.id)
- // Mock cancelInvocations to track what gets skipped
- const cancelInvocationsSpy = jest.spyOn(processor['cyclotronJobQueue'], 'cancelInvocations')
+ // Second batch: invocation2 wakes under a disabled workflow. It must terminate
+ // through the result pipeline (terminal row, metric, log): a silent queue-side
+ // flip would leave the run showing 'running' in the Invocations UI forever.
+ const results2 = await processor.processInvocations([invocation2])
+
+ expect(results2).toHaveLength(1)
+ expect(results2[0].finished).toBe(true)
+ expect(results2[0].canceled).toBe(true)
+ expect(results2[0].error).toBeUndefined()
+ expect(results2[0].logs.map((l) => l.message)).toContain('Run canceled: the workflow is no longer active')
+ expect(results2[0].metrics).toEqual([
+ expect.objectContaining({
+ team_id: hogFlow.team_id,
+ app_source_id: hogFlow.id,
+ metric_kind: 'other',
+ metric_name: 'canceled',
+ count: 1,
+ }),
+ ])
+ // The flow must ride along on the canceled result: the monitoring services key the
+ // terminal lifecycle row off its presence, so without it the row keys `hog_function`,
+ // never collapses the `running` row, and the run stays stuck at `running` in the UI.
+ expect((results2[0].invocation as CyclotronJobInvocationHogFlow).hogFlow?.id).toBe(hogFlow.id)
+ })
- // Second batch: invocation2 should be skipped because workflow is now disabled
- const results2 = (await processor.processInvocations([
- invocation2,
- ])) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]
+ it('attaches the live flow to a cancel-requested run so the terminal row keys as hog_flow', async () => {
+ const hogFlow = hogFlows[0]
+ const invocation = createSerializedHogFlowInvocation(hogFlow, {
+ event: { distinct_id: 'distinct_person_1', properties: { foo: 'bar1' } } as any,
+ })
+ invocation.cancelRequestedAt = DateTime.now()
+
+ const results = await processor.processInvocations([invocation])
+
+ expect(results).toHaveLength(1)
+ expect(results[0].finished).toBe(true)
+ expect(results[0].canceled).toBe(true)
+ expect((results[0].invocation as CyclotronJobInvocationHogFlow).hogFlow?.id).toBe(hogFlow.id)
+ })
- // No results because the workflow is disabled
- expect(results2).toHaveLength(0)
+ it('terminates cancel-requested invocations without loading the flow, so cancel works for deleted flows', async () => {
+ const invocation = createSerializedHogFlowInvocation(hogFlows[0], {
+ event: {
+ distinct_id: 'distinct_A_1',
+ properties: { foo: 'bar1' },
+ } as any,
+ })
+ invocation.functionId = new UUIDT().toString() // flow no longer exists
+ invocation.cancelRequestedAt = DateTime.now()
+
+ const results = await processor.processInvocations([invocation])
- // The invocation should have been canceled (not failed)
- expect(cancelInvocationsSpy).toHaveBeenCalledWith([invocation2])
+ expect(results).toHaveLength(1)
+ expect(results[0].finished).toBe(true)
+ expect(results[0].canceled).toBe(true)
+ expect(results[0].logs.map((l) => l.message)).toContain('Run canceled')
+ expect(results[0].metrics).toEqual([
+ expect.objectContaining({ metric_name: 'canceled', metric_kind: 'other', count: 1 }),
+ ])
+ // Even with no flow to load, the canceled result must still carry the flow id so the
+ // invocation keys the terminal lifecycle row as `hog_flow` (not `hog_function`) and
+ // collapses the earlier `running` row instead of leaving the run stuck at `running`.
+ expect((results[0].invocation as CyclotronJobInvocationHogFlow).hogFlow?.id).toBe(invocation.functionId)
})
})
})
diff --git a/nodejs/src/cdp/rerun/rerun-job.types.ts b/nodejs/src/cdp/rerun/rerun-job.types.ts
index 89839e3976e1..68a808abb606 100644
--- a/nodejs/src/cdp/rerun/rerun-job.types.ts
+++ b/nodejs/src/cdp/rerun/rerun-job.types.ts
@@ -34,7 +34,7 @@ export const rerunWrapperKindFor = (kind: RerunFunctionKind): RerunWrapperFuncti
export const isRerunWrapperKind = (kind: string): kind is RerunWrapperFunctionKind =>
kind === 'hog_function_rerun' || kind === 'hog_flow_rerun'
-export type RerunStatusValue = 'running' | 'succeeded' | 'failed'
+export type RerunStatusValue = 'running' | 'succeeded' | 'failed' | 'canceled'
/**
* Filter shape for a rerun request.
diff --git a/nodejs/src/cdp/services/cyclotron-v2/README.md b/nodejs/src/cdp/services/cyclotron-v2/README.md
index d087dfe046ba..2df09c302ed8 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/README.md
+++ b/nodejs/src/cdp/services/cyclotron-v2/README.md
@@ -18,6 +18,10 @@ for all job payload data (mirrors how the Kafka backend serializes everything in
Creates jobs via `createJob()` / `bulkCreateJobs()`.
The bulk path uses `UNNEST` for efficient batch inserts.
+`cancelJobs()` flags in-flight jobs for cancellation (by ids or all jobs of a function) and pulls parked rows' wake time forward.
+It never writes a terminal status:
+the owning worker observes `cancel_requested_at` on dequeue and performs the actual cancellation together with its lifecycle/metric writes.
+
### Worker (consumer)
Poll-based consumer using `FOR UPDATE SKIP LOCKED` to dequeue batches.
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 4959c9929a74..3f1a672cba85 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -97,6 +97,7 @@ interface RawJobRow {
distinct_id: string | null
person_id: string | null
action_id: string | null
+ cancel_requested_at: string | Date | null
}
async function queryJob(id: string): Promise<RawJobRow> {
@@ -755,6 +756,150 @@ describe('Cyclotron V2', () => {
)
})
})
+
+ describe('cancelJobs', () => {
+ const FAR_FUTURE = () => new Date(Date.now() + 7 * 24 * 3600 * 1000)
+
+ async function seedParked(functionId: string, over?: Partial<CyclotronV2JobInit>): Promise<string> {
+ return await manager.createJob({
+ teamId: 1,
+ queueName: QUEUE,
+ functionId,
+ scheduled: FAR_FUTURE(),
+ ...over,
+ })
+ }
+
+ it('jobIds mode: wakes and flags parked rows, flags running rows in place, leaves terminal rows untouched', async () => {
+ const functionId = uuidv7()
+ const parkedId = await seedParked(functionId)
+ const runningId = await seedParked(functionId)
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'running' WHERE id = $1`, [runningId])
+ const completedId = await seedParked(functionId)
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'completed' WHERE id = $1`, [completedId])
+
+ const result = await manager.cancelJobs({
+ teamId: 1,
+ functionId,
+ jobIds: [parkedId, runningId, completedId, uuidv7()],
+ })
+
+ expect(result).toEqual({ marked: 2, remaining: 0, done: true })
+
+ // Parked row: flagged AND woken, so the worker terminates it promptly
+ // instead of after the remaining (potentially days-long) delay.
+ const parked = await queryJob(parkedId)
+ expect(parked.cancel_requested_at).not.toBeNull()
+ expect(new Date(parked.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+
+ // Running row: flagged only. Its wake is pulled forward by the
+ // worker's release, never by an external write racing the lock.
+ const running = await queryJob(runningId)
+ expect(running.cancel_requested_at).not.toBeNull()
+ expect(new Date(running.scheduled).getTime()).toBeGreaterThan(Date.now())
+
+ // Terminal row: untouched, so a later rerun doesn't inherit a flag.
+ const completed = await queryJob(completedId)
+ expect(completed.cancel_requested_at).toBeNull()
+ })
+
+ it('all mode: flags every in-flight row of the function across queues, and nothing beyond it', async () => {
+ const functionId = uuidv7()
+ const parkedId = await seedParked(functionId)
+ const emailQueueId = await seedParked(functionId, { queueName: 'email' })
+ const excludedQueueId = await seedParked(functionId, { queueName: 'orchestration' })
+ const otherFunctionId = await seedParked(uuidv7())
+ const otherTeamId = await seedParked(functionId, { teamId: 2 })
+
+ const result = await manager.cancelJobs({
+ teamId: 1,
+ functionId,
+ all: true,
+ excludeQueueNames: ['orchestration'],
+ })
+
+ expect(result).toEqual({ marked: 2, remaining: 0, done: true })
+ // A run's job can sit on another queue mid-step (e.g. email) - still flagged.
+ expect((await queryJob(parkedId)).cancel_requested_at).not.toBeNull()
+ expect((await queryJob(emailQueueId)).cancel_requested_at).not.toBeNull()
+ // Excluded queues are neither flagged nor counted as remaining.
+ expect((await queryJob(excludedQueueId)).cancel_requested_at).toBeNull()
+ expect((await queryJob(otherFunctionId)).cancel_requested_at).toBeNull()
+ expect((await queryJob(otherTeamId)).cancel_requested_at).toBeNull()
+ })
+
+ it('reports remaining and done=false when the chunk budget runs out, and the next call finishes', async () => {
+ const functionId = uuidv7()
+ await Promise.all(Array.from({ length: 3 }, () => seedParked(functionId)))
+ const smallChunkManager = createManager({ rescheduleChunkSize: 2, rescheduleMaxChunksPerCall: 1 })
+
+ const first = await smallChunkManager.cancelJobs({ teamId: 1, functionId, all: true })
+ expect(first).toEqual({ marked: 2, remaining: 1, done: false })
+
+ const second = await smallChunkManager.cancelJobs({ teamId: 1, functionId, all: true })
+ expect(second).toEqual({ marked: 1, remaining: 0, done: true })
+
+ await smallChunkManager.disconnect()
+ })
+
+ it('a worker releasing a flagged job wakes it immediately instead of honoring the requested delay', async () => {
+ const functionId = uuidv7()
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
+ const worker = createWorker()
+ const [job] = await dequeueOneBatch(worker)
+ expect(job.id).toBe(id)
+
+ await manager.cancelJobs({ teamId: 1, functionId, jobIds: [id] })
+ await job.reschedule({ scheduledAt: FAR_FUTURE() })
+
+ const row = await queryJob(id)
+ expect(row.status).toBe('available')
+ expect(new Date(row.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+ })
+
+ it('dequeued jobs expose cancelRequestedAt so consumers can terminate instead of executing', async () => {
+ const functionId = uuidv7()
+ const id = await manager.createJob({
+ teamId: 1,
+ queueName: QUEUE,
+ functionId,
+ scheduled: FAR_FUTURE(),
+ })
+ await manager.cancelJobs({ teamId: 1, functionId, jobIds: [id] })
+
+ const worker = createWorker()
+ const [job] = await dequeueOneBatch(worker)
+ expect(job.id).toBe(id)
+ expect(job.cancelRequestedAt).not.toBeNull()
+ })
+
+ it('overwriteExisting re-enqueue clears the flag so a rerun does not instantly self-cancel', async () => {
+ const functionId = uuidv7()
+ const id = await seedParked(functionId)
+ await manager.cancelJobs({ teamId: 1, functionId, jobIds: [id] })
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'canceled' WHERE id = $1`, [id])
+
+ await manager.createJob({ id, teamId: 1, queueName: QUEUE, functionId, overwriteExisting: true })
+
+ const row = await queryJob(id)
+ expect(row.status).toBe('available')
+ expect(row.cancel_requested_at).toBeNull()
+ })
+
+ it.each([
+ ['no selector', {}],
+ ['two selectors', { jobIds: [uuidv7()], all: true }],
+ ])('rejects a call with %s instead of guessing scope', async (_name, selector) => {
+ await expect(manager.cancelJobs({ teamId: 1, functionId: uuidv7(), ...selector })).rejects.toThrow(
+ /exactly one selector/
+ )
+ })
+
+ it('empty jobIds is a no-op', async () => {
+ const result = await manager.cancelJobs({ teamId: 1, functionId: uuidv7(), jobIds: [] })
+ expect(result).toEqual({ marked: 0, remaining: 0, done: true })
+ })
+ })
})
// ── Worker ───────────────────────────────────────────────────────
diff --git a/nodejs/src/cdp/services/cyclotron-v2/index.ts b/nodejs/src/cdp/services/cyclotron-v2/index.ts
index de2c7748b003..5e227a86c390 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/index.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/index.ts
@@ -15,4 +15,6 @@ export type {
CyclotronV2BatchLimit,
CyclotronV2BulkCreateAndCheckInInput,
CyclotronV2JobProducer,
+ CyclotronV2CancelJobsOptions,
+ CyclotronV2CancelJobsResult,
} from './types'
diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
index f63020db9894..297726a80e08 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
@@ -407,6 +407,7 @@ export class CyclotronV2Janitor {
distinctId: row.distinct_id,
personId: row.person_id,
actionId: row.action_id,
+ cancelRequestedAt: null,
ack: () => Promise.resolve(),
fail: () => Promise.resolve(),
reschedule: () => Promise.resolve(),
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 1d3ccd15ae9f..0e27f7f0e348 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -7,6 +7,8 @@ import { logger } from '~/common/utils/logger'
import { sleep } from '~/common/utils/utils'
import {
+ CyclotronV2CancelJobsOptions,
+ CyclotronV2CancelJobsResult,
CyclotronV2InFlightCounts,
CyclotronV2JobInit,
CyclotronV2JobInitSchema,
@@ -90,6 +92,12 @@ const rescheduleFailureCounter = new Counter({
labelNames: ['kind'] as const,
})
+const cancelMarkedCounter = new Counter({
+ name: 'cdp_cyclotron_v2_cancel_marked',
+ help: 'In-flight cyclotron jobs flagged for cancellation, split by the job status at marking time.',
+ labelNames: ['status'] as const,
+})
+
/**
* Thrown when an `overwriteExisting` createJob / bulkCreateJobs hits a row
* that's still in an active state ('available' or 'running'). Callers should
@@ -175,7 +183,8 @@ export class CyclotronV2Manager {
state = EXCLUDED.state,
distinct_id = EXCLUDED.distinct_id,
person_id = EXCLUDED.person_id,
- action_id = EXCLUDED.action_id
+ action_id = EXCLUDED.action_id,
+ cancel_requested_at = NULL
WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')
RETURNING id`
: 'RETURNING id'
@@ -283,7 +292,8 @@ export class CyclotronV2Manager {
distinct_id = EXCLUDED.distinct_id,
person_id = EXCLUDED.person_id,
action_id = EXCLUDED.action_id,
- dequeue_seq = EXCLUDED.dequeue_seq
+ dequeue_seq = EXCLUDED.dequeue_seq,
+ cancel_requested_at = NULL
WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')
RETURNING id`
: 'RETURNING id'
@@ -583,6 +593,111 @@ export class CyclotronV2Manager {
}
}
+ /**
+ * Flag in-flight jobs for cancellation. This never writes a terminal status
+ * itself: the manager has no path to the lifecycle/metric sinks, so the
+ * owning worker performs the actual cancellation (terminal status flip plus
+ * lifecycle row, metric, and log) when it next observes the job. Parked rows
+ * get their wake pulled forward so that happens promptly; rows a worker
+ * currently holds are flagged only, never fighting `lock_id`, because the
+ * worker's release pulls the wake forward via its cancel-aware scheduled
+ * CASE, so they terminate one step later.
+ *
+ * Chunked like `rescheduleParkedJobs` so one call never updates an
+ * unbounded row count; callers loop while `done` is false. Selection
+ * deliberately spans queues: a run's job can sit on another queue (e.g.
+ * 'email') mid-step and still needs to be cancellable. Callers whose
+ * function also owns non-run orchestration jobs exclude those queues via
+ * `excludeQueueNames`.
+ */
+ async cancelJobs(options: CyclotronV2CancelJobsOptions): Promise<CyclotronV2CancelJobsResult> {
+ const { teamId, functionId } = options
+ if ((options.jobIds !== undefined) === (options.all === true)) {
+ throw new Error('cancelJobs requires exactly one selector: jobIds or all')
+ }
+
+ const jobIds = options.jobIds ? [...new Set(options.jobIds)] : undefined
+ if (jobIds && jobIds.length === 0) {
+ return { marked: 0, remaining: 0, done: true }
+ }
+
+ const params: (number | string | string[])[] = [teamId, functionId]
+ let selectorClause = ''
+ if (jobIds) {
+ params.push(jobIds)
+ selectorClause = `AND id = ANY($${params.length}::uuid[])`
+ }
+ if (options.excludeQueueNames?.length) {
+ params.push(options.excludeQueueNames)
+ selectorClause += ` AND queue_name != ALL($${params.length}::text[])`
+ }
+
+ let marked = 0
+
+ // Parked rows: flag + wake. SKIP LOCKED skips rows a concurrent dequeue
+ // is claiming; those turn 'running' and the second UPDATE catches them.
+ const chunkLimitParam = params.length + 1
+ for (let chunk = 0; chunk < this.reschedule.maxChunksPerCall; chunk++) {
+ if (chunk > 0) {
+ await sleep(this.reschedule.chunkSleepMs)
+ }
+ const result = await this.pool.query(
+ `WITH candidates AS (
+ SELECT id FROM cyclotron_jobs
+ WHERE team_id = $1 AND function_id = $2 AND status = 'available'
+ AND cancel_requested_at IS NULL
+ ${selectorClause}
+ LIMIT $${chunkLimitParam}
+ FOR UPDATE SKIP LOCKED
+ )
+ UPDATE cyclotron_jobs j
+ SET cancel_requested_at = NOW(), scheduled = LEAST(j.scheduled, NOW())
+ FROM candidates c
+ WHERE j.id = c.id`,
+ [...params, this.reschedule.chunkSize]
+ )
+ const n = result.rowCount ?? 0
+ marked += n
+ cancelMarkedCounter.labels({ status: 'available' }).inc(n)
+ if (n < this.reschedule.chunkSize) {
+ break
+ }
+ }
+
+ // Rows held by a worker right now: bounded by worker concurrency, so
+ // no chunking or wake write needed.
+ const runningResult = await this.pool.query(
+ `UPDATE cyclotron_jobs
+ SET cancel_requested_at = NOW()
+ WHERE team_id = $1 AND function_id = $2 AND status = 'running'
+ AND cancel_requested_at IS NULL
+ ${selectorClause}`,
+ params
+ )
+ const runningMarked = runningResult.rowCount ?? 0
+ marked += runningMarked
+ cancelMarkedCounter.labels({ status: 'running' }).inc(runningMarked)
+
+ const remainingResult = 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')
+ AND cancel_requested_at IS NULL
+ ${selectorClause}`,
+ params
+ )
+ const remaining = remainingResult.rows[0].count
+
+ logger.info('Cancel sweep completed', {
+ teamId,
+ functionId,
+ mode: jobIds ? 'jobIds' : 'all',
+ marked,
+ remaining,
+ })
+
+ return { marked, remaining, done: remaining === 0 }
+ }
+
/**
* Size the sweep window for the current parked backlog: floor at
* `now + floorSeconds`, width `count / wakeRatePerSecond` clamped to
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index b806fdbe9771..f363f52b63e1 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -79,6 +79,10 @@ export interface CyclotronV2DequeuedJob {
readonly distinctId: string | null
readonly personId: string | null
readonly actionId: string | null
+ // Set by CyclotronV2Manager.cancelJobs. The consumer that dequeued this job is
+ // responsible for terminating it (cancel() plus its own telemetry) instead of
+ // executing it.
+ readonly cancelRequestedAt: DateTime | null
ack(): Promise<void>
fail(): Promise<void>
@@ -125,6 +129,30 @@ export type CyclotronV2RescheduleParkedResult = {
sweepUntil: Date
}
+export type CyclotronV2CancelJobsOptions = {
+ teamId: number
+ functionId: string
+ // Exactly one selector must be provided.
+ // Specific jobs (deduplicated; ids that are unknown or already terminal are ignored):
+ jobIds?: string[]
+ // Every in-flight job of the function:
+ all?: boolean
+ // Queues whose jobs are never flagged (or counted as remaining), e.g. internal
+ // orchestration jobs that are not runs. Applies to both selectors.
+ excludeQueueNames?: string[]
+}
+
+export type CyclotronV2CancelJobsResult = {
+ // In-flight rows newly flagged by this call. Parked rows also had their wake
+ // time pulled forward; rows held by a worker were flagged only and terminate
+ // at their next release.
+ marked: number
+ // In-flight rows matching the selector still unflagged, because the per-call
+ // chunk budget ran out or a row transitioned mid-call. Call again.
+ remaining: number
+ done: boolean
+}
+
/**
* Producer-side surface of `CyclotronV2Manager`. Lets API entrypoints depend
* on the interface (testable, mockable) without pulling the full manager
@@ -144,6 +172,7 @@ export interface CyclotronV2JobProducer {
createJob(input: CyclotronV2JobInit): Promise<string>
countInFlightJobs(teamId: number, functionId: string): Promise<CyclotronV2InFlightCounts>
rescheduleParkedJobs(options: CyclotronV2RescheduleParkedOptions): Promise<CyclotronV2RescheduleParkedResult>
+ cancelJobs(options: CyclotronV2CancelJobsOptions): Promise<CyclotronV2CancelJobsResult>
disconnect(): Promise<void>
}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index dff52877dc19..e5beebb4aa21 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -29,6 +29,7 @@ export interface RawJobRow {
distinct_id: string | null
person_id: string | null
action_id: string | null
+ cancel_requested_at: string | null
lock_id: string
}
@@ -176,7 +177,9 @@ async function updateSelfInTx(
`last_transition = NOW()`,
`transition_count = transition_count + 1`,
`janitor_touch_count = 0`,
- `scheduled = $3`,
+ // A cancel requested while this worker held the job must not sleep the full
+ // next delay before it's observed, so it wakes immediately instead.
+ `scheduled = CASE WHEN cancel_requested_at IS NOT NULL THEN LEAST($3::timestamptz, NOW()) ELSE $3::timestamptz END`,
]
const params: any[] = [jobId, lockId, scheduled]
if (disposition.state !== undefined) {
@@ -324,6 +327,7 @@ export class CyclotronV2Worker {
cyclotron_jobs.distinct_id,
cyclotron_jobs.person_id,
cyclotron_jobs.action_id,
+ cyclotron_jobs.cancel_requested_at,
cyclotron_jobs.lock_id`,
[this.config.queueName, limit, lockId]
)
@@ -385,6 +389,7 @@ export class CyclotronV2Worker {
cyclotron_jobs.distinct_id,
cyclotron_jobs.person_id,
cyclotron_jobs.action_id,
+ cyclotron_jobs.cancel_requested_at,
cyclotron_jobs.lock_id`,
[this.config.queueName, limit, lockId]
)
@@ -421,6 +426,9 @@ export class CyclotronV2Worker {
distinctId: row.distinct_id,
personId: row.person_id,
actionId: row.action_id,
+ cancelRequestedAt: row.cancel_requested_at
+ ? DateTime.fromISO(row.cancel_requested_at, { zone: 'utc' })
+ : null,
async ack(): Promise<void> {
releaseGuard('ack')
@@ -462,7 +470,10 @@ export class CyclotronV2Worker {
// (e.g. wait_until_condition polls) don't accrue touches for
// their whole life and get mistaken for poison pills.
`janitor_touch_count = 0`,
- `scheduled = $3`,
+ // A cancel requested while this worker held the job must not
+ // sleep the full next delay before it's observed, so it
+ // wakes immediately instead.
+ `scheduled = CASE WHEN cancel_requested_at IS NOT NULL THEN LEAST($3::timestamptz, NOW()) ELSE $3::timestamptz END`,
]
const params: any[] = [row.id, lockId, scheduled]
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
index 6ad38d1c2559..5f3620c3b31c 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-kafka.ts
@@ -140,9 +140,8 @@ export class CyclotronJobQueueKafka implements JobQueue {
)
}
- // Kafka jobs don't need explicit dequeue/cancel — they're just dropped
+ // Kafka jobs don't need explicit dequeue — they're just dropped
public async dequeueInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}
- public async cancelInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}
public async heartbeatInvocations(_invocations: CyclotronJobInvocation[]): Promise<void> {}
public async queueInvocationResults(invocationResults: CyclotronJobInvocationResult[]) {
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
index 14bcb321ebaf..cd644ac4afd3 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
@@ -242,6 +242,20 @@ describe('CyclotronJobQueuePostgresV2', () => {
expect(job.fail).toHaveBeenCalledTimes(1)
})
+ it('should call cancel, not ack, on canceled jobs so they never count as completed', async () => {
+ const { queue } = createQueue()
+ const job = createDequeuedJob()
+ ;(queue as any).pendingJobs.set(job.id, job)
+
+ await queue.queueInvocationResults([
+ createResult({ invocation: { ...baseInvocation, id: job.id }, finished: true, canceled: true }),
+ ])
+
+ expect(job.cancel).toHaveBeenCalledTimes(1)
+ expect(job.ack).not.toHaveBeenCalled()
+ expect((queue as any).pendingJobs.has(job.id)).toBe(false)
+ })
+
it('should call reschedule with serialized state on non-finished, non-errored jobs', async () => {
const { queue } = createQueue()
const job = createDequeuedJob()
@@ -327,19 +341,6 @@ describe('CyclotronJobQueuePostgresV2', () => {
})
})
- describe('cancelInvocations', () => {
- it('should call cancel and remove from pending', async () => {
- const { queue } = createQueue()
- const job = createDequeuedJob()
- ;(queue as any).pendingJobs.set(job.id, job)
-
- await queue.cancelInvocations([{ ...baseInvocation, id: job.id }])
-
- expect(job.cancel).toHaveBeenCalledTimes(1)
- expect((queue as any).pendingJobs.has(job.id)).toBe(false)
- })
- })
-
describe('releaseInvocations', () => {
it('should call ack and remove from pending', async () => {
const { queue } = createQueue()
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
index c7071f88a0da..ae1a89a89755 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
@@ -209,6 +209,8 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
if (result.error) {
await job.fail()
+ } else if (result.canceled) {
+ await job.cancel()
} else if (result.finished) {
await job.ack()
} else {
@@ -238,18 +240,6 @@ export class CyclotronJobQueuePostgresV2 implements JobQueue {
)
}
- public async cancelInvocations(invocations: CyclotronJobInvocation[]): Promise<void> {
- await Promise.all(
- invocations.map(async (inv) => {
- const job = this.pendingJobs.get(inv.id)
- if (job) {
- this.pendingJobs.delete(inv.id)
- await job.cancel()
- }
- })
- )
- }
-
public async releaseInvocations(invocations: CyclotronJobInvocation[]): Promise<void> {
await Promise.all(
invocations.map(async (inv) => {
@@ -368,5 +358,9 @@ export function v2JobToInvocation(job: CyclotronV2DequeuedJob): CyclotronJobInvo
invocation.parentRunId = job.parentRunId
}
+ if (job.cancelRequestedAt) {
+ invocation.cancelRequestedAt = job.cancelRequestedAt
+ }
+
return invocation
}
diff --git a/nodejs/src/cdp/services/job-queue/job-queue.interface.ts b/nodejs/src/cdp/services/job-queue/job-queue.interface.ts
index 63802bd3ff23..23b8e9c5f15b 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue.interface.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue.interface.ts
@@ -16,6 +16,5 @@ export interface JobQueue {
queueInvocations(invocations: CyclotronJobInvocation[]): Promise<void>
queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void>
dequeueInvocations(invocations: CyclotronJobInvocation[]): Promise<void>
- cancelInvocations(invocations: CyclotronJobInvocation[]): Promise<void>
heartbeatInvocations(invocations: CyclotronJobInvocation[]): Promise<void>
}
diff --git a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
index d9189b7641b4..303157afac94 100644
--- a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
@@ -185,7 +185,9 @@ export class HogFunctionMonitoringService {
)
}
- if (result.finished || result.error) {
+ // A canceled run is neither a success nor a failure: it carries its own
+ // 'canceled' metric on result.metrics, so the derived terminal metric is skipped.
+ if ((result.finished || result.error) && !result.canceled) {
// Process each timing entry individually instead of totaling them
const timings = isHogFunctionResult(result) ? (result.invocation.state?.timings ?? []) : []
for (const timing of timings) {
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
index 3f02c32157fb..a1001161a2f9 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts
@@ -265,6 +265,30 @@ describe('HogInvocationResultsService', () => {
expect(rows[0].error_message).toBe('Request timed out after 30s')
})
+ it('writes status=canceled on a finished result flagged canceled, with no error fields', async () => {
+ const invocation = createExampleInvocation()
+ service.queueInvocationResults([
+ {
+ invocation,
+ finished: true,
+ canceled: true,
+ error: undefined,
+ logs: [],
+ metrics: [],
+ capturedPostHogEvents: [],
+ warehouseWebhookPayloads: [],
+ messageAssets: [],
+ } as any,
+ ])
+ await service.flush()
+
+ const rows = parseProducedRows(outputs)
+ expect(rows).toHaveLength(1)
+ expect(rows[0].status).toBe('canceled')
+ expect(rows[0].error_kind).toBe('')
+ expect(rows[0].finished_at).not.toBeNull()
+ })
+
it('produces no row for an in-flight result that has not finished and has no error', async () => {
const invocation = createExampleInvocation()
service.queueInvocationResults([
diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
index f80557df1e39..794c375384ed 100644
--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts
@@ -40,11 +40,14 @@ export type HogInvocationResultsServiceOutput = HogInvocationResultsOutput | Cdp
* Lifecycle row produced to ClickHouse via Kafka. Mirrors the columns on the
* hog_invocation_results_data table. Two such rows are produced per
* invocation: one when execution starts (`status='running'`) and one when it
- * finishes (`status='succeeded' | 'failed'`). On a rerun, the cycle repeats
- * with the same `invocation_id`, `is_retry=1`, and `attempts` bumped — the
- * ReplacingMergeTree on `(team_id, function_kind, function_id, invocation_id)`
- * keyed by `version` collapses prior versions at merge time.
+ * finishes (`status='succeeded' | 'failed' | 'canceled'`). On a rerun, the
+ * cycle repeats with the same `invocation_id`, `is_retry=1`, and `attempts`
+ * bumped — the ReplacingMergeTree on
+ * `(team_id, function_kind, function_id, invocation_id)` keyed by `version`
+ * collapses prior versions at merge time.
*/
+export type HogInvocationResultStatus = 'running' | 'succeeded' | 'failed' | 'canceled'
+
export interface HogInvocationResultRow {
team_id: number
// `*_rerun` kinds tag the wrapper row that drives a re-run, so the
@@ -54,7 +57,7 @@ export interface HogInvocationResultRow {
function_id: string
invocation_id: string
parent_run_id: string
- status: 'running' | 'succeeded' | 'failed'
+ status: HogInvocationResultStatus
attempts: number
is_retry: 0 | 1
scheduled_at: string // ISO microsecond DateTime64
@@ -322,7 +325,7 @@ export class HogInvocationResultsService {
*/
queueLifecycleRow(
invocation: CyclotronJobInvocation,
- status: 'running' | 'succeeded' | 'failed',
+ status: HogInvocationResultStatus,
opts: {
error?: unknown
errorKind?: string
@@ -342,7 +345,7 @@ export class HogInvocationResultsService {
private buildLifecycleRow(
invocation: CyclotronJobInvocation,
- status: 'running' | 'succeeded' | 'failed',
+ status: HogInvocationResultStatus,
opts: {
error?: unknown
errorKind?: string
@@ -559,7 +562,11 @@ export class HogInvocationResultsService {
continue
}
- const status: 'succeeded' | 'failed' = result.error ? 'failed' : 'succeeded'
+ const status: HogInvocationResultStatus = result.error
+ ? 'failed'
+ : result.canceled
+ ? 'canceled'
+ : 'succeeded'
this.queueLifecycleRow(result.invocation, status, { error: result.error })
}
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 0ecc91dc3eb2..72db80f065c1 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -214,6 +214,7 @@ export type MinimalAppMetric = {
metric_kind: 'failure' | 'success' | 'other' | 'email' | 'sms' | 'push' | 'billing' | 'fetch'
metric_name:
| 'early_exit'
+ | 'canceled'
| 'triggered'
| 'trigger_failed'
| 'succeeded'
@@ -305,6 +306,9 @@ export type CyclotronJobInvocation = {
queueMetadata?: Record<string, any> | null
// Where the invocation came from (kafka or postgres)
queueSource?: CyclotronJobQueueSource
+ // Cancellation was requested (CyclotronV2Manager.cancelJobs) while this invocation
+ // was in flight. The consumer must terminate it as canceled instead of executing.
+ cancelRequestedAt?: DateTime
}
// The result of an execution
@@ -313,6 +317,10 @@ export type CyclotronJobInvocationResult<T extends CyclotronJobInvocation = Cycl
finished: boolean
/** The invocation deliberately finished without running because its trigger did not match. */
skipped?: boolean
+ // The run was canceled rather than succeeding or failing. Only meaningful with
+ // finished=true and no error: the job row and the lifecycle row both flip to
+ // 'canceled'.
+ canceled?: boolean
error?: any
logs: MinimalLogEntry[]
metrics: MinimalAppMetric[]
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index de6fcb5e42a8..8a7e0805a345 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -4,6 +4,7 @@ export enum PosthogJwtAudience {
RECORDING_API = 'posthog:recording_api',
SUBSCRIPTION_PREFERENCES = 'posthog:messaging:subscription_preferences',
WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',
+ WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',
}
export class JWT {
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index d5746dd9c33d..cae38ef8c4be 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -595,6 +595,17 @@ describe('Workflows E2E (postgres-v2)', () => {
// Function should NOT have been called
expect(mockFetch).not.toHaveBeenCalled()
+
+ // The run must terminate through the result pipeline, not a silent queue flip:
+ // a 'canceled' metric lands and the run is not counted as 'succeeded'.
+ await waitForExpect(() => {
+ const metricNames = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow' && m.value.app_source_id === hogFlowId)
+ .map((m: any) => m.value.metric_name)
+ expect(metricNames).toContain('canceled')
+ expect(metricNames).not.toContain('succeeded')
+ }, 5000)
})
})
diff --git a/nodejs/src/common/api/middleware/internal-api-auth.ts b/nodejs/src/common/api/middleware/internal-api-auth.ts
index 99b5a99a9139..4d6ae7754887 100644
--- a/nodejs/src/common/api/middleware/internal-api-auth.ts
+++ b/nodejs/src/common/api/middleware/internal-api-auth.ts
@@ -26,6 +26,8 @@ const PUBLIC_PATH_PREFIXES = ['/public/', '/_health', '/_ready', '/_metrics', '/
const SCOPED_AUTH_PATH_SUFFIXES = [
// Verified in CdpApi.postHogFlowRescheduleParked against WORKFLOWS_RESCHEDULE_JWT_SECRET.
'/reschedule_parked',
+ // Verified in CdpApi.postHogFlowCancelInvocations against the same key, audience-pinned.
+ '/invocations/cancel',
]
export interface InternalApiAuthOptions {
diff --git a/posthog/api/hog_invocation_cancel.py b/posthog/api/hog_invocation_cancel.py
new file mode 100644
index 000000000000..5a64c110411e
--- /dev/null
+++ b/posthog/api/hog_invocation_cancel.py
@@ -0,0 +1,55 @@
+"""
+Cancel endpoint serializers for `HogFlowViewSet`.
+
+These define the request/response shape for `POST .../hog_flows/{id}/invocations/cancel`.
+The view validates input, then proxies through to the Node CDP worker via
+`cancel_hog_flow_invocations` in `posthog.plugins.plugin_server_api`. The worker side only
+flags cyclotron jobs and wakes parked ones; the workflow workers terminate flagged runs with
+their lifecycle rows, metrics, and logs.
+"""
+
+from rest_framework import serializers
+
+from posthog.api.hog_invocation_rerun import HOG_INVOCATION_RERUN_MAX_COUNT
+
+
+class HogInvocationCancelRequestSerializer(serializers.Serializer):
+ """Cancel in-flight invocations of a workflow. Provide exactly one selector."""
+
+ invocation_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ min_length=1,
+ max_length=HOG_INVOCATION_RERUN_MAX_COUNT,
+ help_text=(
+ "Cancel these specific invocations. "
+ f"Capped at {HOG_INVOCATION_RERUN_MAX_COUNT} per request. Invocations that already "
+ "finished are skipped rather than failing the request."
+ ),
+ )
+ all = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Cancel every in-flight invocation of this workflow, including parked delays and waits.",
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ has_ids = attrs.get("invocation_ids") is not None
+ has_all = attrs.get("all") is True
+ if has_ids == has_all:
+ raise serializers.ValidationError("Provide exactly one of 'invocation_ids' or 'all'.")
+ return attrs
+
+
+class HogInvocationCancelResponseSerializer(serializers.Serializer):
+ """
+ Response from the cancel endpoint. Cancellation is asynchronous: this call flags runs, and
+ the workflow workers terminate them shortly after (immediately for parked runs, at the next
+ step boundary for runs mid-execution). A run stays 'running' in listings until that happens.
+ """
+
+ marked = serializers.IntegerField(help_text="In-flight runs newly flagged for cancellation by this request.")
+ remaining = serializers.IntegerField(
+ help_text="Matching in-flight runs not yet flagged. Non-zero on very large workflows; call again."
+ )
+ done = serializers.BooleanField(help_text="True when no matching in-flight runs remain unflagged.")
diff --git a/posthog/api/hog_invocation_rerun.py b/posthog/api/hog_invocation_rerun.py
index 5b533b1b3d29..44858cc3b21f 100644
--- a/posthog/api/hog_invocation_rerun.py
+++ b/posthog/api/hog_invocation_rerun.py
@@ -31,7 +31,7 @@ class HogInvocationRerunFilterSerializer(serializers.Serializer):
window_start = serializers.DateTimeField(required=True, help_text="Inclusive lower bound on `scheduled_at` (UTC).")
window_end = serializers.DateTimeField(required=True, help_text="Exclusive upper bound on `scheduled_at` (UTC).")
status = serializers.ListField(
- child=serializers.ChoiceField(choices=["running", "succeeded", "failed"]),
+ child=serializers.ChoiceField(choices=["running", "succeeded", "failed", "canceled"]),
required=False,
help_text="Restrict to invocations whose latest status is one of these. Defaults to ['failed'].",
)
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 8a9f0ffeed3c..7965eeefdbf3 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -20,6 +20,7 @@ class PosthogJwtAudience(Enum):
SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"
RECORDING_API = "posthog:recording_api"
WORKFLOWS_RESCHEDULE_PARKED = "posthog:workflows:reschedule_parked"
+ WORKFLOWS_CANCEL_INVOCATIONS = "posthog:workflows:cancel_invocations"
INTEGRATION_SERVICE = "posthog:integration_service"
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index 6891c3ea6ab9..08541efd4c3f 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -161,6 +161,39 @@ def reschedule_hog_flow_parked_jobs(
)
+# Same signing key as reschedule_parked: every workflows route on the CDP API verifies against
+# WORKFLOWS_RESCHEDULE_JWT_SECRET, so the key already spans that one caller/callee surface. The
+# distinct audience still keeps a cancel token useless for reschedule (and vice versa).
+WORKFLOWS_CANCEL_INVOCATIONS_JWT_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.WORKFLOWS_CANCEL_INVOCATIONS,
+ settings_name="WORKFLOWS_RESCHEDULE_JWT_SECRETS",
+ default_ttl=timedelta(minutes=2),
+)
+
+
+def _mint_cancel_invocations_jwt(team_id: int, hog_flow_id: str) -> str:
+ """Short-lived scoped JWT for one invocations/cancel call — a leaked token can only cancel runs
+ of this one team + workflow. Raises when unprovisioned so the call fails closed. Verified in
+ the plugin server's CdpApi.postHogFlowCancelInvocations."""
+ if not WORKFLOWS_CANCEL_INVOCATIONS_JWT_PURPOSE.enabled():
+ raise RuntimeError("WORKFLOWS_RESCHEDULE_JWT_SECRET is not configured — cannot cancel invocations")
+ return WORKFLOWS_CANCEL_INVOCATIONS_JWT_PURPOSE.mint({"team_id": team_id, "hog_flow_id": hog_flow_id})
+
+
+def cancel_hog_flow_invocations(team_id: int, hog_flow_id: str, payload: dict) -> requests.Response:
+ """Flag a workflow's in-flight invocations for cancellation. `payload` carries exactly one
+ selector: {"invocation_ids": [...]} or {"all": true}. The Node side only marks rows and wakes
+ parked ones — the workers terminate them with lifecycle rows and metrics — so a `done: false`
+ response just means another call is needed for the rest. The timeout covers the endpoint's
+ worst-case chunked sweep (chunk sleeps + UPDATEs)."""
+ return internal_requests.post(
+ CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/invocations/cancel",
+ json=payload,
+ headers={"Authorization": f"Bearer {_mint_cancel_invocations_jwt(team_id, hog_flow_id)}"},
+ timeout=30,
+ )
+
+
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",
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index 2b1012f8af3c..c21e2e0c5838 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -640,6 +640,7 @@ export interface HogFunctionPublishResponseApi {
* * `running` - running
* * `succeeded` - succeeded
* * `failed` - failed
+ * * `canceled` - canceled
*/
export type HogInvocationRerunFilterStatusEnumApi =
(typeof HogInvocationRerunFilterStatusEnumApi)[keyof typeof HogInvocationRerunFilterStatusEnumApi]
@@ -648,6 +649,7 @@ export const HogInvocationRerunFilterStatusEnumApi = {
Running: 'running',
Succeeded: 'succeeded',
Failed: 'failed',
+ Canceled: 'canceled',
} as const
/**
diff --git a/products/cdp/frontend/generated/api.zod.ts b/products/cdp/frontend/generated/api.zod.ts
index c0343e7aea6d..c39b76f74b97 100644
--- a/products/cdp/frontend/generated/api.zod.ts
+++ b/products/cdp/frontend/generated/api.zod.ts
@@ -1558,8 +1558,10 @@ export const HogFunctionsRerunCreateBody = /* @__PURE__ */ zod
status: zod
.array(
zod
- .enum(['running', 'succeeded', 'failed'])
- .describe('\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed')
+ .enum(['running', 'succeeded', 'failed', 'canceled'])
+ .describe(
+ '\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed\n\* `canceled` - canceled'
+ )
)
.optional()
.describe("Restrict to invocations whose latest status is one of these. Defaults to ['failed']."),
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 9c8623560ca7..405d0a0cddd7 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -5,6 +5,7 @@ import hashlib
import dataclasses
from copy import deepcopy
from datetime import timedelta
+from time import monotonic
from typing import Any, NamedTuple, Optional, cast
from django.conf import settings
@@ -33,6 +34,10 @@ from posthog.schema import ProductKey
from posthog.api.app_metrics2 import AppMetricsMixin, fetch_app_metric_totals_by_source
from posthog.api.documentation import _FallbackSerializer
+from posthog.api.hog_invocation_cancel import (
+ HogInvocationCancelRequestSerializer,
+ HogInvocationCancelResponseSerializer,
+)
from posthog.api.hog_invocation_rerun import HogInvocationRerunRequestSerializer, HogInvocationRerunResponseSerializer
from posthog.api.hog_invocation_results import (
HogInvocationResultDetailSerializer,
@@ -59,6 +64,7 @@ from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_sour
from posthog.models import Team
from posthog.models.filters import Filter
from posthog.plugins.plugin_server_api import (
+ cancel_hog_flow_invocations,
create_hog_flow_invocation_test,
create_hog_flow_scheduled_invocation,
get_hog_flow_in_flight_count,
@@ -2721,6 +2727,7 @@ class HogFlowViewSet(
"schedule_detail",
"bulk_delete",
"rerun",
+ "cancel_invocations",
"graph",
"action_email",
"publish",
@@ -2885,6 +2892,76 @@ class HogFlowViewSet(
return Response(res.json())
+ @extend_schema(
+ request=HogInvocationCancelRequestSerializer,
+ responses={200: HogInvocationCancelResponseSerializer},
+ )
+ @action(detail=True, methods=["POST"], url_path="invocations/cancel")
+ def cancel_invocations(self, request: Request, *args, **kwargs) -> Response:
+ """
+ Cancel in-flight invocations of this workflow, by id or all at once.
+
+ Cancellation is asynchronous: runs are flagged here, then terminated by
+ the workflow workers, promptly for parked runs (delays and waits) and at
+ the next step boundary for runs mid-execution. Steps that already
+ executed are not undone. Canceled runs can be re-run later via `rerun`.
+ """
+ # Workflow deletes are hard deletes, so a flow deleted with runs still parked has no row
+ # here while its jobs live on. Cancel must still reach those jobs: fall back to the URL id,
+ # which is safe because the service JWT pins team + flow and the sweep filters on both, so
+ # an id that never belonged to this team matches nothing.
+ try:
+ hog_flow = self.get_object()
+ hog_flow_id = str(hog_flow.id)
+ except Http404:
+ hog_flow = None
+ # The row is gone, so get_object's per-object access check never ran. Require
+ # project-wide workflow editor access instead - without this, a member whose editor
+ # access came from per-object grants could cancel any deleted flow's runs by UUID.
+ if not self.user_access_control.check_access_level_for_resource("hog_flow", "editor"):
+ raise exceptions.NotFound()
+ try:
+ hog_flow_id = str(uuid_mod.UUID(self.kwargs["pk"]))
+ except (ValueError, KeyError):
+ raise exceptions.NotFound()
+
+ serializer = HogInvocationCancelRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ invocation_ids = serializer.validated_data.get("invocation_ids")
+ payload: dict = (
+ {"invocation_ids": [str(i) for i in invocation_ids]} if invocation_ids is not None else {"all": True}
+ )
+
+ # One CDP call flags a bounded chunk of rows, so a very large workflow needs several.
+ # Two stopping conditions keep one request from pinning a worker on a pathological
+ # backlog: a cap on the number of calls, and a wall-clock budget so that a
+ # slow-but-responsive CDP cannot stack several near-timeout (30s each) calls into a
+ # multi-minute hold. Either way the response's `done: false` tells the caller to
+ # request again for the rest.
+ sweep_deadline = monotonic() + 20
+ data: dict = {"marked": 0, "remaining": 0, "done": False}
+ for _ in range(5):
+ res = cancel_hog_flow_invocations(team_id=self.team_id, hog_flow_id=hog_flow_id, payload=payload)
+ if res.status_code != 200:
+ raise exceptions.APIException(detail=res.text, code="cancel_failed")
+ page = res.json()
+ data = {
+ "marked": data["marked"] + page.get("marked", 0),
+ "remaining": page.get("remaining", 0),
+ "done": page.get("done", False),
+ }
+ if data["done"] or monotonic() >= sweep_deadline:
+ break
+
+ if hog_flow is not None:
+ self._report_workflow_action(
+ "hog_flow_invocations_cancel_requested",
+ hog_flow,
+ {"mode": "ids" if invocation_ids is not None else "all", "marked": data["marked"]},
+ )
+ return Response(data)
+
def _emit_resource_edited(self, instance: HogFlow) -> None:
# Realtime "edited elsewhere" signal so an open builder (or another tab) can refresh instead of
# clobbering edits made via a different channel (UI/MCP/API). Fires for every channel; the
diff --git a/products/workflows/backend/api/test/test_hog_flow_access_control.py b/products/workflows/backend/api/test/test_hog_flow_access_control.py
index 42d81e4d2170..8a0040c20b17 100644
--- a/products/workflows/backend/api/test/test_hog_flow_access_control.py
+++ b/products/workflows/backend/api/test/test_hog_flow_access_control.py
@@ -1,5 +1,6 @@
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -34,6 +35,8 @@ TRIGGER_ACTION = {
# Any UUID — the parent workflow's object-level check rejects before the schedule is ever looked up.
MISSING_SCHEDULE_ID = "00000000-0000-0000-0000-000000000000"
+CANCEL_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_invocations"
+
class TestHogFlowResourceRegistration(SimpleTestCase):
def test_hog_flow_is_a_controllable_resource(self):
@@ -256,3 +259,42 @@ class TestHogFlowAccessControl(ClickhouseTestMixin, APIBaseTest):
self._create_access_control(self.no_access_user, resource_id=str(self.hog_flow.id), access_level="none")
self.client.force_login(self.no_access_user)
self.assertEqual(self.client.get(self._detail_url()).status_code, status.HTTP_200_OK)
+
+ def test_deleted_flow_cancel_requires_resource_level_editor(self):
+ # A deleted flow has no row, so the cancel fallback can't run the per-object check.
+ # A member whose editor access came only from a per-object grant must not be able to
+ # cancel a different (deleted) flow's runs by UUID.
+ other_flow = self._create_workflow(name="deleted_workflow")
+ deleted_id = str(other_flow.id)
+ other_flow.delete()
+
+ self._create_project_default(access_level="none")
+ self._create_access_control(self.editor_user, resource_id=str(self.hog_flow.id), access_level="editor")
+ self.client.force_login(self.editor_user)
+
+ with patch(CANCEL_PROXY) as mock_cancel:
+ response = self.client.post(
+ f"{self._detail_url(deleted_id)}/invocations/cancel/", data={"all": True}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_cancel.assert_not_called()
+
+ def test_deleted_flow_cancel_allowed_with_resource_level_editor(self):
+ other_flow = self._create_workflow(name="deleted_workflow")
+ deleted_id = str(other_flow.id)
+ other_flow.delete()
+
+ self._create_project_default(access_level="editor")
+ self.client.force_login(self.editor_user)
+
+ with patch(
+ CANCEL_PROXY,
+ return_value=MagicMock(status_code=200, json=lambda: {"marked": 1, "remaining": 0, "done": True}),
+ ) as mock_cancel:
+ response = self.client.post(
+ f"{self._detail_url(deleted_id)}/invocations/cancel/", data={"all": True}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, getattr(response, "data", response.content))
+ mock_cancel.assert_called_once()
diff --git a/products/workflows/backend/api/test/test_hog_flow_cancel.py b/products/workflows/backend/api/test/test_hog_flow_cancel.py
new file mode 100644
index 000000000000..a2cf3932df48
--- /dev/null
+++ b/products/workflows/backend/api/test/test_hog_flow_cancel.py
@@ -0,0 +1,104 @@
+import uuid
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+
+CANCEL_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_invocations"
+
+
+def _cdp_response(marked: int = 1, remaining: int = 0, done: bool = True) -> MagicMock:
+ return MagicMock(status_code=200, json=lambda: {"marked": marked, "remaining": remaining, "done": done})
+
+
+class TestHogFlowCancelInvocations(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+
+ def _cancel(self, data: dict):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/invocations/cancel/",
+ data=data,
+ format="json",
+ )
+
+ def test_cancel_by_ids_proxies_with_team_and_flow_pinned(self):
+ invocation_id = str(uuid.uuid4())
+ with patch(CANCEL_PROXY, return_value=_cdp_response()) as mock_cancel:
+ response = self._cancel({"invocation_ids": [invocation_id]})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"marked": 1, "remaining": 0, "done": True}
+ mock_cancel.assert_called_once_with(
+ team_id=self.team.id,
+ hog_flow_id=str(self.hog_flow.id),
+ payload={"invocation_ids": [invocation_id]},
+ )
+
+ def test_cancel_all_repeats_until_done_and_aggregates_marked(self):
+ # A very large workflow can't be flagged in one bounded sweep. The endpoint must keep
+ # calling while the CDP side reports rows remaining, and aggregate the marked counts.
+ with patch(
+ CANCEL_PROXY,
+ side_effect=[_cdp_response(marked=100, remaining=40, done=False), _cdp_response(marked=40)],
+ ) as mock_cancel:
+ response = self._cancel({"all": True})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"marked": 140, "remaining": 0, "done": True}
+ assert mock_cancel.call_count == 2
+ assert mock_cancel.call_args.kwargs["payload"] == {"all": True}
+
+ @parameterized.expand(
+ [
+ ("no_selector", {}),
+ ("both_selectors", {"invocation_ids": [str(uuid.uuid4())], "all": True}),
+ # An empty list is not a valid selector: it must 400 at Django, not fall
+ # through to the CDP proxy and surface the Node 400 as a 500.
+ ("empty_ids", {"invocation_ids": []}),
+ ]
+ )
+ def test_cancel_rejects_ambiguous_selectors(self, _name, data):
+ with patch(CANCEL_PROXY) as mock_cancel:
+ response = self._cancel(data)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ mock_cancel.assert_not_called()
+
+ def test_cancel_reaches_parked_runs_of_a_deleted_flow(self):
+ # Workflow deletes are hard deletes, so a flow deleted with runs still parked has no row.
+ # The cancel endpoint must still proxy for the URL id instead of 404ing before the sweep.
+ flow_id = str(self.hog_flow.id)
+ self.hog_flow.delete()
+
+ with patch(CANCEL_PROXY, return_value=_cdp_response()) as mock_cancel:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/invocations/cancel/",
+ data={"all": True},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ mock_cancel.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, payload={"all": True})
+
+ def test_cancel_rejects_a_malformed_flow_id_without_proxying(self):
+ with patch(CANCEL_PROXY) as mock_cancel:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/not-a-uuid/invocations/cancel/",
+ data={"all": True},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ mock_cancel.assert_not_called()
+
+ def test_cancel_surfaces_cdp_failure_without_reporting_success(self):
+ with patch(CANCEL_PROXY, return_value=MagicMock(status_code=503, text="cyclotron unavailable")):
+ response = self._cancel({"all": True})
+
+ assert response.status_code >= 500
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index afd964a3f509..0fe7f1e2a6c6 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -906,6 +906,34 @@ export interface HogFlowInvocationApi {
use_draft?: boolean
}
+/**
+ * Cancel in-flight invocations of a workflow. Provide exactly one selector.
+ */
+export interface HogInvocationCancelRequestApi {
+ /**
+ * Cancel these specific invocations. Capped at 10000 per request. Invocations that already finished are skipped rather than failing the request.
+ * @minItems 1
+ * @maxItems 10000
+ */
+ invocation_ids?: string[]
+ /** Cancel every in-flight invocation of this workflow, including parked delays and waits. */
+ all?: boolean
+}
+
+/**
+ * Response from the cancel endpoint. Cancellation is asynchronous: this call flags runs, and
+ * the workflow workers terminate them shortly after (immediately for parked runs, at the next
+ * step boundary for runs mid-execution). A run stays 'running' in listings until that happens.
+ */
+export interface HogInvocationCancelResponseApi {
+ /** In-flight runs newly flagged for cancellation by this request. */
+ marked: number
+ /** Matching in-flight runs not yet flagged. Non-zero on very large workflows; call again. */
+ remaining: number
+ /** True when no matching in-flight runs remain unflagged. */
+ done: boolean
+}
+
export interface AppMetricSeriesApi {
name: string
values: number[]
@@ -1013,6 +1041,7 @@ export interface HogFlowPublishResponseApi {
* * `running` - running
* * `succeeded` - succeeded
* * `failed` - failed
+ * * `canceled` - canceled
*/
export type HogInvocationRerunFilterStatusEnumApi =
(typeof HogInvocationRerunFilterStatusEnumApi)[keyof typeof HogInvocationRerunFilterStatusEnumApi]
@@ -1021,6 +1050,7 @@ export const HogInvocationRerunFilterStatusEnumApi = {
Running: 'running',
Succeeded: 'succeeded',
Failed: 'failed',
+ Canceled: 'canceled',
} as const
/**
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 6a36f6a3312b..5c95dcc30310 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -35,6 +35,8 @@ import type {
HogFlowsMetricsTotalsRetrieveParams,
HogFlowsReputationRetrieveParams,
HogFlowsRevisionsListParams,
+ HogInvocationCancelRequestApi,
+ HogInvocationCancelResponseApi,
HogInvocationRerunRequestApi,
HogInvocationRerunResponseApi,
HogInvocationResultApi,
@@ -545,6 +547,32 @@ export const hogFlowsInvocationsCreate = async (
})
}
+export const getHogFlowsInvocationsCancelCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/invocations/cancel/`
+}
+
+/**
+ * Cancel in-flight invocations of this workflow, by id or all at once.
+ *
+ * Cancellation is asynchronous: runs are flagged here, then terminated by
+ * the workflow workers, promptly for parked runs (delays and waits) and at
+ * the next step boundary for runs mid-execution. Steps that already
+ * executed are not undone. Canceled runs can be re-run later via `rerun`.
+ */
+export const hogFlowsInvocationsCancelCreate = async (
+ projectId: string,
+ id: string,
+ hogInvocationCancelRequestApi?: HogInvocationCancelRequestApi,
+ options?: RequestInit
+): Promise<HogInvocationCancelResponseApi> => {
+ return apiMutator<HogInvocationCancelResponseApi>(getHogFlowsInvocationsCancelCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(hogInvocationCancelRequestApi),
+ })
+}
+
export const getHogFlowsLogsRetrieveUrl = (projectId: string, id: string, params?: HogFlowsLogsRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 40d5840e074b..deee26b9adee 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2107,6 +2107,35 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Cancel in-flight invocations of this workflow, by id or all at once.
+ *
+ * Cancellation is asynchronous: runs are flagged here, then terminated by
+ * the workflow workers, promptly for parked runs (delays and waits) and at
+ * the next step boundary for runs mid-execution. Steps that already
+ * executed are not undone. Canceled runs can be re-run later via `rerun`.
+ */
+export const hogFlowsInvocationsCancelCreateBodyInvocationIdsMax = 10000
+
+export const hogFlowsInvocationsCancelCreateBodyAllDefault = false
+
+export const HogFlowsInvocationsCancelCreateBody = /* @__PURE__ */ zod
+ .object({
+ invocation_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(hogFlowsInvocationsCancelCreateBodyInvocationIdsMax)
+ .optional()
+ .describe(
+ 'Cancel these specific invocations. Capped at 10000 per request. Invocations that already finished are skipped rather than failing the request.'
+ ),
+ all: zod
+ .boolean()
+ .default(hogFlowsInvocationsCancelCreateBodyAllDefault)
+ .describe('Cancel every in-flight invocation of this workflow, including parked delays and waits.'),
+ })
+ .describe('Cancel in-flight invocations of a workflow. Provide exactly one selector.')
+
export const hogFlowsPublishCreateBodyConfirmDefault = false
export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
@@ -2154,8 +2183,10 @@ export const HogFlowsRerunCreateBody = /* @__PURE__ */ zod
status: zod
.array(
zod
- .enum(['running', 'succeeded', 'failed'])
- .describe('\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed')
+ .enum(['running', 'succeeded', 'failed', 'canceled'])
+ .describe(
+ '\* `running` - running\n\* `succeeded` - succeeded\n\* `failed` - failed\n\* `canceled` - canceled'
+ )
)
.optional()
.describe("Restrict to invocations whose latest status is one of these. Defaults to ['failed']."),
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 08bd52dbebdf..282a2ac7f5e0 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -60,6 +60,9 @@ tools:
hog-flows-email-sending-suspension-retrieve:
operation: hog_flows_email_sending_suspension_retrieve
enabled: false
+ hog-flows-invocations-cancel-create:
+ operation: hog_flows_invocations_cancel_create
+ enabled: false
hog-flows-invocations-create:
operation: hog_flows_invocations_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0c7ac3efafaa..7388787810af 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39846,10 +39846,39 @@ export namespace Schemas {
overwrite?: boolean;
}
+ /**
+ * Cancel in-flight invocations of a workflow. Provide exactly one selector.
+ */
+ export interface HogInvocationCancelRequest {
+ /**
+ * Cancel these specific invocations. Capped at 10000 per request. Invocations that already finished are skipped rather than failing the request.
+ * @minItems 1
+ * @maxItems 10000
+ */
+ invocation_ids?: string[];
+ /** Cancel every in-flight invocation of this workflow, including parked delays and waits. */
+ all?: boolean;
+ }
+
+ /**
+ * Response from the cancel endpoint. Cancellation is asynchronous: this call flags runs, and
+ * the workflow workers terminate them shortly after (immediately for parked runs, at the next
+ * step boundary for runs mid-execution). A run stays 'running' in listings until that happens.
+ */
+ export interface HogInvocationCancelResponse {
+ /** In-flight runs newly flagged for cancellation by this request. */
+ marked: number;
+ /** Matching in-flight runs not yet flagged. Non-zero on very large workflows; call again. */
+ remaining: number;
+ /** True when no matching in-flight runs remain unflagged. */
+ done: boolean;
+ }
+
/**
* * `running` - running
* * `succeeded` - succeeded
* * `failed` - failed
+ * * `canceled` - canceled
*/
export type HogInvocationRerunFilterStatusEnum = typeof HogInvocationRerunFilterStatusEnum[keyof typeof HogInvocationRerunFilterStatusEnum];
@@ -39858,6 +39887,7 @@ export namespace Schemas {
Running: 'running',
Succeeded: 'succeeded',
Failed: 'failed',
+ Canceled: 'canceled',
} as const;
/**