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): stop batch runs mid-enrollment (#83638)

Harley Alexanderee493648721b
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index 43f9cd2a861e..ddbc6f5f8434 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -1825,6 +1825,115 @@ describe('CDP API', () => {
})
})
+ describe('hogflow cancel batch job 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_BATCH_JWT_PURPOSE, so drift on either side breaks here.
+ const batchFlowId = new UUIDT().toString()
+ const batchJobId = new UUIDT().toString()
+
+ const mintBatchToken = (
+ teamId: number,
+ hogFlowId: string,
+ {
+ secret = 'local-dev-workflows-reschedule-jwt',
+ audience = 'posthog:workflows:cancel_batch',
+ batchJob = batchJobId,
+ } = {}
+ ) =>
+ jwt.sign({ team_id: teamId, hog_flow_id: hogFlowId, batch_job_id: batchJob }, secret, {
+ audience,
+ expiresIn: '2m',
+ })
+ const batchAuth = (teamId: number, hogFlowId: string) => ({
+ Authorization: `Bearer ${mintBatchToken(teamId, hogFlowId)}`,
+ })
+ const batchCancelUrl = (teamId: number) =>
+ `/api/projects/${teamId}/hog_flows/${batchFlowId}/batch_jobs/${batchJobId}/cancel`
+
+ beforeEach(() => {
+ mockCancelJobs = jest.fn().mockResolvedValue({ marked: 2, 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 sweeps the batch run', async () => {
+ const res = await supertest(app).post(batchCancelUrl(team.id)).set(batchAuth(team.id, batchFlowId)).send({})
+
+ expect(res.status).toEqual(200)
+ expect(res.body).toEqual({ marked: 2, remaining: 0, done: true })
+ expect(mockCancelJobs).toHaveBeenCalledWith(
+ expect.objectContaining({ teamId: team.id, functionId: batchFlowId, parentRunId: batchJobId })
+ )
+ })
+
+ it.each([
+ ['no token', () => ({})],
+ [
+ 'a token signed with the wrong key',
+ () => ({
+ Authorization: `Bearer ${mintBatchToken(team.id, batchFlowId, { secret: 'wrong-key' })}`,
+ }),
+ ],
+ [
+ "another workflow's token",
+ () => ({ Authorization: `Bearer ${mintBatchToken(team.id, new UUIDT().toString())}` }),
+ ],
+ ["another team's token", () => ({ Authorization: `Bearer ${mintBatchToken(team.id + 1, batchFlowId)}` })],
+ [
+ // A captured token must not be replayable against a sibling batch run of the
+ // same workflow: the batch_job_id claim has to match the URL.
+ "another batch run's token",
+ () => ({
+ Authorization: `Bearer ${mintBatchToken(team.id, batchFlowId, {
+ batchJob: new UUIDT().toString(),
+ })}`,
+ }),
+ ],
+ [
+ // The batch purpose shares its signing key with the other workflows purposes, so
+ // the audience is the only thing keeping an invocations-cancel token out of here.
+ 'an invocations-cancel-audience token',
+ () => ({
+ Authorization: `Bearer ${mintBatchToken(team.id, batchFlowId, {
+ audience: 'posthog:workflows:cancel_invocations',
+ })}`,
+ }),
+ ],
+ ])('rejects a request with %s', async (_desc, headers) => {
+ const res = await supertest(app).post(batchCancelUrl(team.id)).set(headers()).send({})
+
+ expect(res.status).toEqual(401)
+ expect(mockCancelJobs).not.toHaveBeenCalled()
+ })
+
+ it('fails closed when the batch cancel JWT key is not provisioned', async () => {
+ const savedJwt = api['cancelBatchJwt']
+ api['cancelBatchJwt'] = new ScopedServiceJwt(PosthogJwtAudience.WORKFLOWS_CANCEL_BATCH, '')
+ try {
+ const res = await supertest(app)
+ .post(batchCancelUrl(team.id))
+ .set(batchAuth(team.id, batchFlowId))
+ .send({})
+
+ expect(res.status).toEqual(503)
+ expect(mockCancelJobs).not.toHaveBeenCalled()
+ } finally {
+ api['cancelBatchJwt'] = 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 0690136eb78b..14fed64116d4 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -145,11 +145,12 @@ export class CdpApi {
private batchExportHogFunctionService: BatchExportHogFunctionService
private groupsManager: GroupsManagerService
private batchResolverProducer: CyclotronV2JobProducer | null
- // 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,
+ // Scoped auth for the reschedule_parked and 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
+ private cancelBatchJwt: ScopedServiceJwt
constructor(
private config: PluginsServerConfig,
@@ -209,6 +210,10 @@ export class CdpApi {
PosthogJwtAudience.WORKFLOWS_CANCEL_INVOCATIONS,
config.WORKFLOWS_RESCHEDULE_JWT_SECRET || ''
)
+ this.cancelBatchJwt = new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOWS_CANCEL_BATCH,
+ config.WORKFLOWS_RESCHEDULE_JWT_SECRET || ''
+ )
}
public get service(): PluginServerService {
@@ -284,6 +289,10 @@ export class CdpApi {
'/api/projects/:team_id/hog_flows/:id/invocations/cancel',
asyncHandler(this.postHogFlowCancelInvocations)
)
+ router.post(
+ '/api/projects/:team_id/hog_flows/:id/batch_jobs/:batch_job_id/cancel',
+ asyncHandler(this.postHogFlowCancelBatchJob)
+ )
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()))
@@ -1034,24 +1043,28 @@ 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.
+ // touch another team or flow. Routes scoped tighter than a workflow (batch cancel) pass the
+ // narrower claims via extraClaims and every one must match too. Writes the 401 itself and
+ // returns false on any mismatch.
private verifyScopedWorkflowJwt(
jwt: ScopedServiceJwt,
req: ModifiedRequest,
res: express.Response,
- label: string
+ label: string,
+ extraClaims?: Record<string, 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
+ let claims: Record<string, unknown> | 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) {
+ const extrasMatch = !extraClaims || Object.entries(extraClaims).every(([key, value]) => claims?.[key] === value)
+ if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id || !extrasMatch) {
res.status(401).json({ error: `Unauthorized: Invalid ${label} token` })
return false
}
@@ -1223,6 +1236,63 @@ export class CdpApi {
}
}
+ // Stop a batch run: flag its resolver orchestration job and every child run for
+ // cancellation in one sweep — they share parent_run_id, so one selector covers both.
+ // The resolver's in-transaction tombstone check plus Django's repeat-until-done loop
+ // make this converge: once the resolver is flagged it can commit at most the one page
+ // that already held its row lock, and that page's children surface in the next sweep's
+ // remaining count.
+ //
+ // Auth mirrors the other workflows CDP calls: a per-call JWT minted by Django, pinned
+ // to this team + workflow, on its own audience.
+ private postHogFlowCancelBatchJob = 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.cancelBatchJwt.enabled) {
+ return res.status(503).json({
+ error: 'Workflows scoped auth not configured (WORKFLOWS_RESCHEDULE_JWT_SECRET unset)',
+ })
+ }
+
+ const { team_id, id, batch_job_id } = req.params
+
+ // batch_job_id is pinned in the claims too: without it, a captured token could stop
+ // any sibling batch of the same workflow for the token's lifetime.
+ if (!this.verifyScopedWorkflowJwt(this.cancelBatchJwt, req, res, 'cancel', { batch_job_id })) {
+ return
+ }
+
+ const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)
+ if (!team) {
+ return res.status(404).json({ error: 'Team not found' })
+ }
+
+ if (batch_job_id.length > 200) {
+ return res.status(400).json({ error: 'batch_job_id is too long' })
+ }
+
+ const result = await this.batchResolverProducer.cancelJobs({
+ teamId: team.id,
+ functionId: id,
+ parentRunId: batch_job_id,
+ })
+ return res.json({
+ marked: result.marked,
+ remaining: result.remaining,
+ done: result.done,
+ })
+ } catch (e) {
+ logger.error('Error cancelling hog flow batch job', {
+ 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-batch-resolve.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
index e3979c8e8fc4..bc7f44e22793 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
@@ -1,3 +1,5 @@
+import { DateTime } from 'luxon'
+
import { HogFlow } from '~/cdp/schema/hogflow'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { parseJSON } from '~/common/utils/json-parse'
@@ -121,7 +123,7 @@ describe('CdpCyclotronWorkerBatchResolve', () => {
beforeEach(() => {
queueAppMetrics = jest.fn()
- bulkCreateAndCheckIn = jest.fn().mockResolvedValue(undefined)
+ bulkCreateAndCheckIn = jest.fn().mockResolvedValue({ newJobIds: [] })
release = jest.fn().mockResolvedValue(undefined)
// Masking itself is covered by hog-masker.service.test.ts; stubbing the partition
// here is what lets each case fix which runs are masked and assert how the consumer
@@ -230,5 +232,65 @@ describe('CdpCyclotronWorkerBatchResolve', () => {
expect(release).toHaveBeenCalledTimes(1)
expect(triggeredMetrics()).toHaveLength(0)
})
+
+ it('terminates the resolver instead of scheduling another page when the check-in is refused by a cancel', async () => {
+ // The engine refuses the page when a cancel flag landed mid-build: nothing
+ // committed, so the queued running rows and mask claims must be undone (these
+ // children will never run) and the resolver must terminate, not retry.
+ bulkCreateAndCheckIn.mockResolvedValue({ newJobIds: [], cancelRequested: true })
+ const cancel = jest.fn().mockResolvedValue(undefined)
+ const reschedule = jest.fn()
+ Object.assign(consumer, {
+ hogFunctionMonitoringService: {
+ queueAppMetrics,
+ queueLogs: jest.fn(),
+ flush: jest.fn().mockResolvedValue(undefined),
+ },
+ })
+
+ await (consumer as any).processOnePage({ bulkCreateAndCheckIn, reschedule, cancel }, state)
+ await rowsService.flush()
+
+ expect(producedRows()).toHaveLength(0)
+ expect(release).toHaveBeenCalledTimes(1)
+ expect(triggeredMetrics()).toHaveLength(0)
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(reschedule).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('cancel-flagged resolver jobs', () => {
+ it('terminates on dequeue without fetching a page, even when the state is unparseable', async () => {
+ const getBlastRadiusPersons = jest.fn()
+ const queueLogs = jest.fn()
+ const flush = jest.fn().mockResolvedValue(undefined)
+ const consumer = Object.create(CdpCyclotronWorkerBatchResolve.prototype)
+ Object.assign(consumer, {
+ hogFlowBatchPersonQueryService: { getBlastRadiusPersons },
+ hogFunctionMonitoringService: { queueLogs, flush },
+ })
+ const cancel = jest.fn().mockResolvedValue(undefined)
+ const job = {
+ id: 'job-1',
+ teamId: team.id,
+ functionId: hogFlow.id,
+ parentRunId: 'batch-job-1',
+ cancelRequestedAt: DateTime.now(),
+ // Unparseable on purpose: the cancel must not depend on state surviving
+ // schema drift across deploys.
+ state: Buffer.from('not json'),
+ cancel,
+ }
+
+ await (consumer as any).processResolverJob(job)
+
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(getBlastRadiusPersons).not.toHaveBeenCalled()
+ // The stop is visible on the batch run's log stream, keyed by parent run id.
+ expect(queueLogs).toHaveBeenCalledTimes(1)
+ const [logs] = queueLogs.mock.calls[0]
+ expect(logs[0].log_source_id).toEqual('batch-job-1')
+ expect(flush).toHaveBeenCalled()
+ })
})
})
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
index 4264cfdb0dfe..2b091b46952c 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
@@ -45,7 +45,7 @@ const counterBatchHogFlowResolverPagesProcessed = new Counter({
const counterBatchHogFlowResolverJobs = new Counter({
name: 'cdp_batch_hog_flow_resolver_jobs',
help: 'Batch hog flow resolver jobs by lifecycle outcome',
- labelNames: ['outcome'], // started | completed | failed
+ labelNames: ['outcome'], // started | completed | failed | canceled
})
/**
@@ -96,6 +96,14 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
}
private async processResolverJob(job: CyclotronV2DequeuedJob): Promise<void> {
+ // Checked before state deserialization so a cancel lands even on a job whose state
+ // this deploy can no longer parse. `parentRunId` carries the batch job id
+ // independently of state, so the log still keys to the run.
+ if (job.cancelRequestedAt) {
+ await this.cancelResolverJob(job)
+ return
+ }
+
let state: BatchResolverState
try {
state = deserializeResolverState(job.state)
@@ -173,6 +181,40 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
}
}
+ /**
+ * Terminate a cancel-flagged resolver job: no further pages, and no terminal status
+ * PUT — Django flips the batch job's status itself as part of the cancel request, and
+ * the internal status endpoint absorbs terminal states, so a racing completion still
+ * resolves consistently. The log lands on the batch run's log stream so the stop is
+ * visible next to its runs. Flushes monitoring itself because the cancel paths return
+ * before processResolverJob's finally-flush.
+ */
+ private async cancelResolverJob(job: CyclotronV2DequeuedJob): Promise<void> {
+ counterBatchHogFlowResolverJobs.labels({ outcome: 'canceled' }).inc()
+ this.hogFunctionMonitoringService.queueLogs(
+ [
+ {
+ team_id: job.teamId,
+ log_source: 'hog_flow',
+ log_source_id: job.parentRunId ?? job.functionId ?? '',
+ instance_id: job.parentRunId ?? job.id,
+ ...logEntry('info', 'Batch run canceled. The remaining audience will not receive this workflow.'),
+ },
+ ],
+ 'hog_flow'
+ )
+ await this.hogFunctionMonitoringService.flush().catch((err) => {
+ logger.warn('⚠️', `${this.name} - failed to flush monitoring after resolver cancel`, {
+ error: serializeError(err),
+ })
+ })
+ await job.cancel()
+ logger.info('🛑', `${this.name} - resolver job canceled`, {
+ jobId: job.id,
+ parentRunId: job.parentRunId,
+ })
+ }
+
/**
* Fetch one page of audience and atomically enqueue children + advance state.
* On fetch failure, retries via cyclotron reschedule with backoff — cursor
@@ -317,8 +359,9 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
newState.pendingTerminal = 'completed'
}
+ let checkIn: { newJobIds: string[]; cancelRequested?: boolean }
try {
- await job.bulkCreateAndCheckIn({
+ checkIn = await job.bulkCreateAndCheckIn({
newJobs: children,
selfDisposition: {
kind: 'reschedule',
@@ -339,6 +382,19 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
throw err
}
+ if (checkIn.cancelRequested) {
+ // A cancel flag landed while this page was being built, so the check-in was
+ // refused and nothing committed. Undo the mask claims and queued `running`
+ // rows exactly like the failure path — these children will never run — then
+ // terminate the resolver instead of scheduling another page.
+ await release()
+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor(
+ notMasked.map((invocation) => invocation.id)
+ )
+ await this.cancelResolverJob(job)
+ return
+ }
+
// Queued only after a successful commit: a failed page is replayed, so metrics
// emitted for it would double-count once the replay re-evaluates masking.
if (masked.length) {
diff --git a/nodejs/src/cdp/services/cyclotron-v2/README.md b/nodejs/src/cdp/services/cyclotron-v2/README.md
index 2df09c302ed8..f5e003ac210a 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/README.md
+++ b/nodejs/src/cdp/services/cyclotron-v2/README.md
@@ -18,9 +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.
+`cancelJobs()` flags in-flight jobs for cancellation (by ids, by parent run, 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.
+`bulkCreateAndCheckIn()` re-checks the flag inside its transaction and refuses the whole page when set, so a fan-out in progress cannot commit jobs after a cancel sweep counted zero remaining.
### Worker (consumer)
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 3f1a672cba85..7a9f4a1583fd 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -828,6 +828,65 @@ describe('Cyclotron V2', () => {
expect((await queryJob(otherTeamId)).cancel_requested_at).toBeNull()
})
+ it("parentRunId mode: flags the run's resolver job and children, and nothing beyond the run", async () => {
+ const functionId = uuidv7()
+ const parentRunId = uuidv7()
+ // The resolver orchestration job and its children share parent_run_id but
+ // sit on different queues - one selector must flag all of them.
+ const resolverId = await seedParked(functionId, { queueName: 'orchestration', parentRunId })
+ const parkedChildId = await seedParked(functionId, { parentRunId })
+ const runningChildId = await seedParked(functionId, { parentRunId })
+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'running' WHERE id = $1`, [runningChildId])
+ const otherRunId = await seedParked(functionId, { parentRunId: uuidv7() })
+ const otherTeamId = await seedParked(functionId, { parentRunId, teamId: 2 })
+
+ const result = await manager.cancelJobs({ teamId: 1, functionId, parentRunId })
+
+ expect(result).toEqual({ marked: 3, remaining: 0, done: true })
+ // Parked rows (resolver included) are flagged AND woken; the running child is
+ // flagged in place, its wake pulled forward by the worker's release.
+ const resolver = await queryJob(resolverId)
+ expect(resolver.cancel_requested_at).not.toBeNull()
+ expect(new Date(resolver.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+ expect((await queryJob(parkedChildId)).cancel_requested_at).not.toBeNull()
+ expect((await queryJob(runningChildId)).cancel_requested_at).not.toBeNull()
+ expect((await queryJob(otherRunId)).cancel_requested_at).toBeNull()
+ expect((await queryJob(otherTeamId)).cancel_requested_at).toBeNull()
+ })
+
+ it('rejects an empty parentRunId instead of widening to the whole workflow', async () => {
+ await expect(manager.cancelJobs({ teamId: 1, functionId: uuidv7(), parentRunId: '' })).rejects.toThrow(
+ /non-empty/
+ )
+ })
+
+ it('bulkCreateAndCheckIn refuses the page when a cancel flag landed while the worker held the job', async () => {
+ const functionId = uuidv7()
+ const parentRunId = uuidv7()
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId, parentRunId })
+ const worker = createWorker()
+ const [job] = await dequeueOneBatch(worker)
+ expect(job.id).toBe(id)
+
+ // The mid-page window: the flag lands after the worker dequeued (and checked)
+ // the job but before it commits the page it is building.
+ await manager.cancelJobs({ teamId: 1, functionId, parentRunId })
+
+ const result = await job.bulkCreateAndCheckIn({
+ newJobs: [{ teamId: 1, queueName: QUEUE, functionId, parentRunId }],
+ selfDisposition: { kind: 'reschedule', scheduledAt: FAR_FUTURE() },
+ })
+
+ expect(result).toEqual({ newJobIds: [], cancelRequested: true })
+ // Nothing committed: no child row, and the self row kept its state.
+ expect(await totalJobCount()).toBe(1)
+ const row = await queryJob(id)
+ expect(row.status).toBe('running')
+ // The job is still held - the caller disposes of it.
+ await job.cancel()
+ expect((await queryJob(id)).status).toBe('canceled')
+ })
+
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)))
@@ -889,6 +948,7 @@ describe('Cyclotron V2', () => {
it.each([
['no selector', {}],
['two selectors', { jobIds: [uuidv7()], all: true }],
+ ['two selectors (parentRunId and all)', { parentRunId: 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/
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 0e27f7f0e348..fc1c9a117f4f 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -612,8 +612,19 @@ export class CyclotronV2Manager {
*/
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 selectorCount = [
+ options.jobIds !== undefined,
+ options.all === true,
+ options.parentRunId !== undefined,
+ ].filter(Boolean).length
+ if (selectorCount !== 1) {
+ throw new Error('cancelJobs requires exactly one selector: jobIds, parentRunId, or all')
+ }
+ // Rejected rather than treated as unset: the SQL builder below tests truthiness, so an
+ // empty string would leave the selector clause empty and silently widen a parent-run
+ // cancel to every in-flight job of the workflow.
+ if (options.parentRunId !== undefined && options.parentRunId.length === 0) {
+ throw new Error('cancelJobs parentRunId must be a non-empty string')
}
const jobIds = options.jobIds ? [...new Set(options.jobIds)] : undefined
@@ -626,6 +637,9 @@ export class CyclotronV2Manager {
if (jobIds) {
params.push(jobIds)
selectorClause = `AND id = ANY($${params.length}::uuid[])`
+ } else if (options.parentRunId) {
+ params.push(options.parentRunId)
+ selectorClause = `AND parent_run_id = $${params.length}`
}
if (options.excludeQueueNames?.length) {
params.push(options.excludeQueueNames)
@@ -690,7 +704,7 @@ export class CyclotronV2Manager {
logger.info('Cancel sweep completed', {
teamId,
functionId,
- mode: jobIds ? 'jobIds' : 'all',
+ mode: jobIds ? 'jobIds' : options.parentRunId ? 'parentRunId' : 'all',
marked,
remaining,
})
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index f363f52b63e1..7e3193aa0d78 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -89,7 +89,16 @@ export interface CyclotronV2DequeuedJob {
reschedule(options?: CyclotronV2RescheduleOptions): Promise<void>
cancel(): Promise<void>
heartbeat(): Promise<void>
- bulkCreateAndCheckIn(input: CyclotronV2BulkCreateAndCheckInInput): Promise<{ newJobIds: string[] }>
+ // `cancelRequested: true` means the check-in was refused: a cancel flag landed on this
+ // job (CyclotronV2Manager.cancelJobs) before the transaction took its row lock, so
+ // nothing was inserted and the job is STILL HELD — the caller must dispose of it
+ // (normally via cancel()). The refusal is checked inside the same transaction that
+ // inserts the new jobs, so a cancel sweep can never lose a page to this race: either
+ // the page committed before the flag (and the sweep's remaining-count sees its jobs),
+ // or the flag landed first and the page is refused.
+ bulkCreateAndCheckIn(
+ input: CyclotronV2BulkCreateAndCheckInInput
+ ): Promise<{ newJobIds: string[]; cancelRequested?: boolean }>
}
export type CyclotronV2ManagerConfig = {
@@ -137,6 +146,9 @@ export type CyclotronV2CancelJobsOptions = {
jobIds?: string[]
// Every in-flight job of the function:
all?: boolean
+ // Every in-flight job of one parent run (a batch job): the resolver orchestration
+ // job and all child runs it enqueued. Must be non-empty when provided.
+ parentRunId?: string
// 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[]
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index e5beebb4aa21..05f23001c3f7 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -197,7 +197,7 @@ async function updateSelfInTx(
function assertSelfRowAffected(rowCount: number | null, jobId: string, kind: string): void {
if (rowCount !== 1) {
throw new Error(
- `bulkCreateAndCheckIn(${kind}) self UPDATE matched ${rowCount} rows for job ${jobId} — lock_id may have been reassigned`
+ `bulkCreateAndCheckIn(${kind}) self row matched ${rowCount} rows for job ${jobId} — lock_id may have been reassigned`
)
}
}
@@ -544,7 +544,9 @@ export class CyclotronV2Worker {
)
},
- async bulkCreateAndCheckIn(input: CyclotronV2BulkCreateAndCheckInInput): Promise<{ newJobIds: string[] }> {
+ async bulkCreateAndCheckIn(
+ input: CyclotronV2BulkCreateAndCheckInInput
+ ): Promise<{ newJobIds: string[]; cancelRequested?: boolean }> {
releaseGuard('bulkCreateAndCheckIn')
// Validate new jobs up front, outside the TX, so a malformed
@@ -555,6 +557,27 @@ export class CyclotronV2Worker {
try {
await client.query('BEGIN')
+ // Cancel tombstone, checked inside the transaction. The FOR UPDATE takes the
+ // self row's lock, so this serializes against cancelJobs' flag write: a flag
+ // that committed first refuses the whole page here (nothing inserted), and a
+ // page that locked first commits before the flag can land — the cancel
+ // sweep's remaining-count then still sees its jobs. Without this check, a
+ // page could commit after a cancel sweep counted zero remaining, leaving
+ // jobs that never get flagged.
+ const selfRow = await client.query<{ cancel_requested_at: string | null }>(
+ `SELECT cancel_requested_at FROM cyclotron_jobs
+ WHERE id = $1 AND lock_id = $2
+ FOR UPDATE`,
+ [row.id, lockId]
+ )
+ assertSelfRowAffected(selfRow.rowCount, row.id, 'precheck')
+ if (selfRow.rows[0].cancel_requested_at !== null) {
+ await client.query('ROLLBACK')
+ // The job was never released — hand it back to the caller to dispose.
+ released = false
+ return { newJobIds: [], cancelRequested: true }
+ }
+
const newJobIds = await insertNewJobsInTx(client, newJobs)
await updateSelfInTx(client, row.id, lockId, input.selfDisposition)
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 8a7e0805a345..97b8ca15925e 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -5,6 +5,7 @@ export enum PosthogJwtAudience {
SUBSCRIPTION_PREFERENCES = 'posthog:messaging:subscription_preferences',
WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',
WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',
+ WORKFLOWS_CANCEL_BATCH = 'posthog:workflows:cancel_batch',
}
export class JWT {
diff --git a/nodejs/src/common/api/middleware/internal-api-auth.test.ts b/nodejs/src/common/api/middleware/internal-api-auth.test.ts
index 715831c7d0f4..b4c6c554b132 100644
--- a/nodejs/src/common/api/middleware/internal-api-auth.test.ts
+++ b/nodejs/src/common/api/middleware/internal-api-auth.test.ts
@@ -188,9 +188,13 @@ describe('createInternalApiAuthMiddleware', () => {
expect(res.status).not.toHaveBeenCalled()
})
- it('should skip auth for scoped-JWT routes, which authenticate in their handler', () => {
+ it.each([
+ ['/api/projects/1/hog_flows/some-uuid/reschedule_parked'],
+ ['/api/projects/1/hog_flows/some-uuid/invocations/cancel'],
+ ['/api/projects/1/hog_flows/some-uuid/batch_jobs/some-job-id/cancel'],
+ ])('should skip auth for scoped-JWT route %s, which authenticates in its handler', (path) => {
const middleware = createInternalApiAuthMiddleware({ secret: 'test-secret' })
- const req = mockRequest('/api/projects/1/hog_flows/some-uuid/reschedule_parked', {})
+ const req = mockRequest(path, {})
const res = mockResponse()
const next = jest.fn()
@@ -200,6 +204,24 @@ describe('createInternalApiAuthMiddleware', () => {
expect(res.status).not.toHaveBeenCalled()
})
+ it.each([
+ // batch_invocations' last segment is a caller-controlled :parent_run_id and its handler
+ // verifies no token, so the literal id "cancel" must not inherit the scoped-JWT exemption.
+ ['/api/projects/1/hog_flows/some-uuid/batch_invocations/cancel'],
+ ['/api/some/other/route/cancel'],
+ ['/api/projects/1/hog_flows/some-uuid/reschedule_parked/extra'],
+ ])('should still require the secret for %s despite resembling a scoped route', (path) => {
+ const middleware = createInternalApiAuthMiddleware({ secret: 'test-secret' })
+ const req = mockRequest(path, {})
+ const res = mockResponse()
+ const next = jest.fn()
+
+ middleware(req, res, next)
+
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
it('should allow custom excluded path prefixes', () => {
const middleware = createInternalApiAuthMiddleware({
secret: 'test-secret',
diff --git a/nodejs/src/common/api/middleware/internal-api-auth.ts b/nodejs/src/common/api/middleware/internal-api-auth.ts
index 4d6ae7754887..b6b8e96a4592 100644
--- a/nodejs/src/common/api/middleware/internal-api-auth.ts
+++ b/nodejs/src/common/api/middleware/internal-api-auth.ts
@@ -22,12 +22,18 @@ const PUBLIC_PATH_PREFIXES = ['/public/', '/_health', '/_ready', '/_metrics', '/
// Routes that authenticate with their own scoped JWT instead of the shared internal secret, so
// their callers never need INTERNAL_API_SECRET (the goal of retiring it). Each entry must be a
-// route whose handler enforces its own auth — never add a suffix here without one.
-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',
+// full-path pattern anchored to exactly one route whose handler enforces its own auth — never
+// add a pattern here without one. Suffix matching is not safe for this list: some routes take a
+// caller-controlled trailing segment (e.g. batch_invocations' :parent_run_id), so a bare suffix
+// like '/cancel' would let a crafted id inherit the exemption and reach a handler that never
+// checks a token.
+const SCOPED_AUTH_PATH_PATTERNS = [
+ // CdpApi.postHogFlowRescheduleParked, verified against WORKFLOWS_RESCHEDULE_JWT_SECRET.
+ /^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/reschedule_parked$/,
+ // CdpApi.postHogFlowCancelInvocations, verified against the same key, audience-pinned.
+ /^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/invocations\/cancel$/,
+ // CdpApi.postHogFlowCancelBatchJob, verified against the same key, audience-pinned.
+ /^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/batch_jobs\/[^/]+\/cancel$/,
]
export interface InternalApiAuthOptions {
@@ -58,7 +64,7 @@ export function createInternalApiAuthMiddleware(options: InternalApiAuthOptions)
}
// Scoped-JWT routes enforce their own auth in the handler.
- if (SCOPED_AUTH_PATH_SUFFIXES.some((suffix) => req.path.endsWith(suffix))) {
+ if (SCOPED_AUTH_PATH_PATTERNS.some((pattern) => pattern.test(req.path))) {
next()
return
}
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 7965eeefdbf3..39512adebe4b 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -21,6 +21,7 @@ class PosthogJwtAudience(Enum):
RECORDING_API = "posthog:recording_api"
WORKFLOWS_RESCHEDULE_PARKED = "posthog:workflows:reschedule_parked"
WORKFLOWS_CANCEL_INVOCATIONS = "posthog:workflows:cancel_invocations"
+ WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"
INTEGRATION_SERVICE = "posthog:integration_service"
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index 08541efd4c3f..8aede4b9aa65 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -180,6 +180,38 @@ def _mint_cancel_invocations_jwt(team_id: int, hog_flow_id: str) -> str:
return WORKFLOWS_CANCEL_INVOCATIONS_JWT_PURPOSE.mint({"team_id": team_id, "hog_flow_id": hog_flow_id})
+# Same shared workflows signing key as the purposes above, on its own audience.
+WORKFLOWS_CANCEL_BATCH_JWT_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.WORKFLOWS_CANCEL_BATCH,
+ settings_name="WORKFLOWS_RESCHEDULE_JWT_SECRETS",
+ default_ttl=timedelta(minutes=2),
+)
+
+
+def _mint_cancel_batch_jwt(team_id: int, hog_flow_id: str, batch_job_id: str) -> str:
+ """Short-lived scoped JWT for one batch_jobs/:id/cancel call — a leaked token can only stop
+ this one batch run of this one team + workflow. Raises when unprovisioned so the call fails
+ closed. Verified in the plugin server's CdpApi.postHogFlowCancelBatchJob."""
+ if not WORKFLOWS_CANCEL_BATCH_JWT_PURPOSE.enabled():
+ raise RuntimeError("WORKFLOWS_RESCHEDULE_JWT_SECRET is not configured — cannot stop the batch run")
+ return WORKFLOWS_CANCEL_BATCH_JWT_PURPOSE.mint(
+ {"team_id": team_id, "hog_flow_id": hog_flow_id, "batch_job_id": batch_job_id}
+ )
+
+
+def cancel_hog_flow_batch_job(team_id: int, hog_flow_id: str, batch_job_id: str) -> requests.Response:
+ """Flag a batch run's resolver job and all its child runs for cancellation — they share
+ parent_run_id, so the CDP side sweeps both with one selector. Bounded like the invocation
+ cancel: `done: false` 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}/batch_jobs/{batch_job_id}/cancel",
+ json={},
+ headers={"Authorization": f"Bearer {_mint_cancel_batch_jwt(team_id, hog_flow_id, batch_job_id)}"},
+ timeout=30,
+ )
+
+
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
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index cd30b06d34c7..bc3d69285fd4 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -602,6 +602,8 @@ SPECTACULAR_SETTINGS = {
"TicketTagsMatchEnum": "products.conversations.backend.api.ticket_filters.TICKET_TAGS_MATCH_CHOICES",
"TicketSortOrderEnum": "products.conversations.backend.api.ticket_filters.TICKET_SORT_ORDER_CHOICES",
"BatchImportStatusEnum": "products.managed_migrations.backend.models.batch_imports.BatchImport.Status",
+ # Shared by HogFlowBatchJob.status and HogFlowBatchJobCancelResponse.status (same choice set).
+ "HogFlowBatchJobStatusEnum": "products.workflows.backend.models.hog_flow_batch_job.HogFlowBatchJob.State",
# Shared by ExperimentMetricsRecalculation.status and ActiveRecalculationRun.status (same choice set).
"MetricsRecalculationStatusEnum": (
"products.experiments.backend.models.experiment.ExperimentMetricsRecalculation.Status"
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 405d0a0cddd7..011ea0a98d40 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -64,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_batch_job,
cancel_hog_flow_invocations,
create_hog_flow_invocation_test,
create_hog_flow_scheduled_invocation,
@@ -93,7 +94,10 @@ from products.notifications.backend.facade.api import publish_resource_edited
from products.workflows.backend.api.action_redirects import compute_action_redirects
from products.workflows.backend.api.graph_operations import _deep_merge, apply_graph_operations
from products.workflows.backend.api.graph_validation import validate_graph
-from products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer
+from products.workflows.backend.api.hog_flow_batch_job import (
+ HogFlowBatchJobCancelResponseSerializer,
+ HogFlowBatchJobSerializer,
+)
from products.workflows.backend.api.message_assets import (
MessageAssetContentRequestSerializer,
MessageAssetSerializer,
@@ -2728,6 +2732,7 @@ class HogFlowViewSet(
"bulk_delete",
"rerun",
"cancel_invocations",
+ "cancel_batch_job",
"graph",
"action_email",
"publish",
@@ -4284,6 +4289,80 @@ class HogFlowViewSet(
serializer = HogFlowBatchJobSerializer(batch_jobs, many=True)
return Response(serializer.data)
+ @extend_schema(
+ request=None,
+ parameters=[
+ OpenApiParameter(
+ "batch_job_id",
+ OpenApiTypes.UUID,
+ location=OpenApiParameter.PATH,
+ description="ID of the batch run to stop.",
+ ),
+ ],
+ responses={200: HogFlowBatchJobCancelResponseSerializer},
+ )
+ @action(detail=True, methods=["POST"], url_path="batch_jobs/(?P<batch_job_id>[^/.]+)/cancel")
+ def cancel_batch_job(self, request: Request, *args, **kwargs) -> Response:
+ """
+ Stop a batch run: no more of its audience is enrolled, and every run of it
+ still in flight is canceled.
+
+ Stopping is asynchronous: runs are flagged here, then terminated by the
+ workflow workers. Steps that already executed, like sent messages, are not
+ undone. Already-finished batch runs are left untouched.
+ """
+ hog_flow = self.get_object()
+
+ try:
+ batch_job = HogFlowBatchJob.objects.get(id=kwargs["batch_job_id"], hog_flow=hog_flow, team_id=self.team_id)
+ except (HogFlowBatchJob.DoesNotExist, DjangoValidationError, ValueError):
+ # DjangoValidationError fires when the id is not a parseable UUID — surface
+ # as 404 rather than a 500 reported to error tracking.
+ raise exceptions.NotFound("Batch job not found")
+
+ non_terminal = {
+ HogFlowBatchJob.State.WAITING,
+ HogFlowBatchJob.State.QUEUED,
+ HogFlowBatchJob.State.ACTIVE,
+ }
+ if batch_job.status not in non_terminal:
+ return Response({"status": batch_job.status, "marked": 0, "remaining": 0, "done": True})
+
+ # One CDP call flags a bounded chunk of rows; a large batch needs several. Same
+ # shape as cancel_invocations — `done: false` after the cap tells the caller to
+ # request again for the rest.
+ data: dict = {"marked": 0, "remaining": 0, "done": False}
+ for _ in range(5):
+ res = cancel_hog_flow_batch_job(
+ team_id=self.team_id, hog_flow_id=str(hog_flow.id), batch_job_id=str(batch_job.id)
+ )
+ 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"]:
+ break
+
+ if data["done"]:
+ # Conditional so a completion that landed mid-cancel wins over the flip; the
+ # resolver's own terminal write absorbs the reverse race. `.update()` bypasses
+ # auto_now, so stamp updated_at explicitly.
+ HogFlowBatchJob.objects.filter(id=batch_job.id, status__in=non_terminal).update(
+ status=HogFlowBatchJob.State.CANCELLED, updated_at=timezone.now()
+ )
+
+ batch_job.refresh_from_db()
+ self._report_workflow_action(
+ "hog_flow_batch_job_cancel_requested",
+ hog_flow,
+ {"batch_job_id": str(batch_job.id), "marked": data["marked"], "done": data["done"]},
+ )
+ return Response({"status": batch_job.status, **data})
+
@extend_schema(methods=["GET"], responses=HogFlowScheduleSerializer(many=True))
@extend_schema(methods=["POST"], request=HogFlowScheduleSerializer, responses=HogFlowScheduleSerializer)
# GET returns a bare list (no pagination) and ignores the viewset's HogFlow filterset; disable both so the
diff --git a/products/workflows/backend/api/hog_flow_batch_job.py b/products/workflows/backend/api/hog_flow_batch_job.py
index 2887531ddb28..6b365b1053f3 100644
--- a/products/workflows/backend/api/hog_flow_batch_job.py
+++ b/products/workflows/backend/api/hog_flow_batch_job.py
@@ -51,3 +51,22 @@ class HogFlowBatchJobSerializer(serializers.ModelSerializer):
validated_data["team_id"] = team_id
return super().create(validated_data=validated_data)
+
+
+class HogFlowBatchJobCancelResponseSerializer(serializers.Serializer):
+ """
+ Response from the batch job cancel endpoint. Stopping is asynchronous: this call flags the
+ run's audience fan-out and its in-flight child runs, and the workflow workers terminate
+ them shortly after. Messages already sent are not recalled.
+ """
+
+ status = serializers.ChoiceField(
+ choices=HogFlowBatchJob.State.choices,
+ help_text="The batch run's status after this request. 'cancelled' once every in-flight run is flagged; "
+ "a completion that raced the stop wins and is reported instead.",
+ )
+ marked = serializers.IntegerField(help_text="In-flight runs newly flagged for cancellation by this request.")
+ remaining = serializers.IntegerField(
+ help_text="In-flight runs of this batch not yet flagged. Non-zero on very large runs; call again."
+ )
+ done = serializers.BooleanField(help_text="True when no in-flight runs of this batch remain unflagged.")
diff --git a/products/workflows/backend/api/test/test_hog_flow_cancel.py b/products/workflows/backend/api/test/test_hog_flow_cancel.py
index a2cf3932df48..735b639c8b96 100644
--- a/products/workflows/backend/api/test/test_hog_flow_cancel.py
+++ b/products/workflows/backend/api/test/test_hog_flow_cancel.py
@@ -7,8 +7,13 @@ from parameterized import parameterized
from rest_framework import status
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
CANCEL_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_invocations"
+CANCEL_BATCH_PROXY = "products.workflows.backend.api.hog_flow.cancel_hog_flow_batch_job"
+BATCH_DISPATCH = (
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+)
def _cdp_response(marked: int = 1, remaining: int = 0, done: bool = True) -> MagicMock:
@@ -102,3 +107,103 @@ class TestHogFlowCancelInvocations(APIBaseTest):
response = self._cancel({"all": True})
assert response.status_code >= 500
+
+
+class TestHogFlowCancelBatchJob(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.hog_flow = HogFlow.objects.create(team=self.team, name="Test", trigger={}, actions=[], edges=[])
+
+ def _create_batch_job(self, job_status: str) -> HogFlowBatchJob:
+ # Creating a batch job dispatches to the CDP worker via post_save; stub it out.
+ with patch(BATCH_DISPATCH):
+ return HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.hog_flow, status=job_status)
+
+ def _cancel(self, batch_job_id):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}/batch_jobs/{batch_job_id}/cancel/"
+ )
+
+ def test_cancel_active_batch_job_flags_run_and_marks_cancelled(self):
+ batch_job = self._create_batch_job("active")
+
+ with patch(CANCEL_BATCH_PROXY, return_value=_cdp_response(marked=5)) as mock_cancel:
+ response = self._cancel(batch_job.id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"status": "cancelled", "marked": 5, "remaining": 0, "done": True}
+ mock_cancel.assert_called_once_with(
+ team_id=self.team.id,
+ hog_flow_id=str(self.hog_flow.id),
+ batch_job_id=str(batch_job.id),
+ )
+ batch_job.refresh_from_db()
+ assert batch_job.status == "cancelled"
+
+ @parameterized.expand([("completed",), ("cancelled",), ("failed",)])
+ def test_cancel_terminal_batch_job_is_a_no_op(self, terminal_status):
+ batch_job = self._create_batch_job(terminal_status)
+
+ with patch(CANCEL_BATCH_PROXY) as mock_cancel:
+ response = self._cancel(batch_job.id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["status"] == terminal_status
+ mock_cancel.assert_not_called()
+
+ def test_cancel_does_not_clobber_a_run_that_completed_mid_request(self):
+ # The resolver's terminal write can land between the flag sweep and the status
+ # flip; the genuine completion must win over the cancel.
+ batch_job = self._create_batch_job("active")
+
+ def complete_job_then_respond(**kwargs):
+ HogFlowBatchJob.objects.filter(id=batch_job.id).update(status="completed")
+ return _cdp_response(marked=0)
+
+ with patch(CANCEL_BATCH_PROXY, side_effect=complete_job_then_respond):
+ response = self._cancel(batch_job.id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["status"] == "completed"
+ batch_job.refresh_from_db()
+ assert batch_job.status == "completed"
+
+ def test_cancel_not_done_after_sweep_cap_leaves_status_untouched(self):
+ # A pathological backlog can outlast the bounded sweeps. The run must not read
+ # as terminally cancelled while unflagged runs are still in flight.
+ batch_job = self._create_batch_job("active")
+
+ with patch(CANCEL_BATCH_PROXY, return_value=_cdp_response(marked=10, remaining=5, done=False)) as mock_cancel:
+ response = self._cancel(batch_job.id)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"status": "active", "marked": 50, "remaining": 5, "done": False}
+ assert mock_cancel.call_count == 5
+ batch_job.refresh_from_db()
+ assert batch_job.status == "active"
+
+ @parameterized.expand(
+ [
+ ("unknown_id", str(uuid.uuid4())),
+ # A non-UUID id raises DjangoValidationError during query prep, before any
+ # SQL - it must surface as 404, not a 500 reported to error tracking.
+ ("malformed_id", "not-a-uuid"),
+ ]
+ )
+ def test_cancel_missing_batch_job_404s(self, _name, batch_job_id):
+ with patch(CANCEL_BATCH_PROXY) as mock_cancel:
+ response = self._cancel(batch_job_id)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ mock_cancel.assert_not_called()
+
+ def test_cancel_batch_job_of_another_flow_404s(self):
+ other_flow = HogFlow.objects.create(team=self.team, name="Other", trigger={}, actions=[], edges=[])
+ with patch(BATCH_DISPATCH):
+ other_job = HogFlowBatchJob.objects.create(team=self.team, hog_flow=other_flow, status="active")
+
+ with patch(CANCEL_BATCH_PROXY) as mock_cancel:
+ response = self._cancel(other_job.id)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ mock_cancel.assert_not_called()
diff --git a/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
index 81236d1457f9..98d5192c1bd6 100644
--- a/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
@@ -1,9 +1,18 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { type ReactNode, useMemo } from 'react'
import * as greekPng from '@posthog/brand/hoggies/png/greek'
import { IconClock } from '@posthog/icons'
-import { LemonCollapse, LemonDivider, LemonTag, ProfilePicture, Spinner, Tooltip } from '@posthog/lemon-ui'
+import {
+ LemonButton,
+ LemonCollapse,
+ LemonDialog,
+ LemonDivider,
+ LemonTag,
+ ProfilePicture,
+ Spinner,
+ Tooltip,
+} from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
@@ -39,14 +48,50 @@ function SectionHeading({ children }: { children: ReactNode }): JSX.Element {
return <h3 className="text-xs font-semibold uppercase tracking-wide text-muted mb-1">{children}</h3>
}
-function BatchRunHeader({ job }: { job: HogFlowBatchJob }): JSX.Element {
+const STOPPABLE_STATUSES: HogFlowBatchJob['status'][] = ['waiting', 'queued', 'active']
+
+function BatchRunHeader({ job, hogFlowId }: { job: HogFlowBatchJob; hogFlowId: string }): JSX.Element {
+ const { cancellingJobIds } = useValues(batchWorkflowJobsLogic({ id: hogFlowId }))
+ const { cancelBatchJob } = useActions(batchWorkflowJobsLogic({ id: hogFlowId }))
+
return (
<div className="flex gap-2 w-full justify-between">
<div className="flex items-center gap-2 min-w-0">
<strong className="truncate">{job.id}</strong>
- <LemonTag type={STATUS_TAG_TYPE[job.status] ?? 'default'}>{job.status}</LemonTag>
+ <LemonTag type={STATUS_TAG_TYPE[job.status] ?? 'default'}>
+ {/* The stored enum value is 'cancelled'; display American spelling. */}
+ {job.status === 'cancelled' ? 'canceled' : job.status}
+ </LemonTag>
</div>
<div className="flex items-center gap-2">
+ {STOPPABLE_STATUSES.includes(job.status) ? (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ status="danger"
+ loading={cancellingJobIds.includes(job.id)}
+ onClick={(e) => {
+ // The header row toggles the collapse panel; stopping a run shouldn't.
+ e.stopPropagation()
+ LemonDialog.open({
+ title: 'Stop this batch run?',
+ // Two sentences of copy; the default dialog width spans the screen.
+ maxWidth: '30rem',
+ content:
+ 'No more of the audience will receive this workflow, and every run ' +
+ 'still in flight is canceled. Messages already sent are not recalled.',
+ primaryButton: {
+ children: 'Stop run',
+ status: 'danger',
+ onClick: () => cancelBatchJob(job.id),
+ },
+ secondaryButton: { children: 'Keep running' },
+ })
+ }}
+ >
+ Stop
+ </LemonButton>
+ ) : null}
<TZLabel title="Created at" time={job.created_at} />
<LemonDivider vertical className="h-full" />
{job.created_by ? (
@@ -186,7 +231,7 @@ export function WorkflowBatchInvocations({ id }: { id: string }): JSX.Element {
<LemonCollapse
panels={jobs.map((job) => ({
key: job.id,
- header: <BatchRunHeader job={job} />,
+ header: <BatchRunHeader job={job} hogFlowId={id} />,
content: <BatchRunInvocations job={job} hogFlowId={id} />,
}))}
/>
diff --git a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
index 85749d07a5ca..39c158893640 100644
--- a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
+++ b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.test.ts
@@ -1,11 +1,15 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { lemonToast } from '@posthog/lemon-ui'
+
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { HogFlowBatchJobCancelResponseApi } from 'products/workflows/frontend/generated/api.schemas'
+
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
const WORKFLOW_ID = 'wf-batch-1'
@@ -13,9 +17,11 @@ const WORKFLOW_ID = 'wf-batch-1'
describe('batchWorkflowJobsLogic', () => {
let logic: ReturnType<typeof batchWorkflowJobsLogic.build>
let getCalls: number
+ let cancelResponse: HogFlowBatchJobCancelResponseApi
beforeEach(() => {
getCalls = 0
+ cancelResponse = { status: 'cancelled', marked: 1, remaining: 0, done: true }
useMocks({
get: {
'/api/environments/:team_id/hog_flows/:id/batch_jobs/': () => {
@@ -23,12 +29,19 @@ describe('batchWorkflowJobsLogic', () => {
return [200, []]
},
},
+ post: {
+ '/api/projects/:team_id/hog_flows/:id/batch_jobs/:batch_job_id/cancel/': () => [200, cancelResponse],
+ },
})
initKeaTests()
logic = batchWorkflowJobsLogic({ id: WORKFLOW_ID })
logic.mount()
})
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
it('fetches once when entering the invocations tab', async () => {
router.actions.push(urls.workflow(WORKFLOW_ID, 'invocations'))
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
@@ -70,4 +83,25 @@ describe('batchWorkflowJobsLogic', () => {
await expectLogic(logic).toDispatchActions(['loadBatchWorkflowJobsSuccess'])
expect(getCalls).toBe(2)
})
+
+ // The cancel endpoint returns `done: true` with a non-cancelled status when a completion won the
+ // stop race; the toast must reflect the status, not report a stop that didn't happen.
+ it.each([
+ { case: 'the sweep cancelled the run', status: 'cancelled', done: true, toast: 'success' },
+ { case: 'a completion won the stop race', status: 'completed', done: true, toast: 'info' },
+ { case: 'runs are still in flight', status: 'active', done: false, toast: 'warning' },
+ ] as const)('cancelBatchJob reports "$toast" when $case', async ({ status, done, toast }) => {
+ cancelResponse = { status, marked: 0, remaining: done ? 0 : 1, done }
+ const successSpy = jest.spyOn(lemonToast, 'success')
+ const infoSpy = jest.spyOn(lemonToast, 'info')
+ const warningSpy = jest.spyOn(lemonToast, 'warning')
+
+ await expectLogic(logic, () => {
+ logic.actions.cancelBatchJob('job-1')
+ }).toDispatchActions(['cancelBatchJobComplete'])
+
+ expect(successSpy).toHaveBeenCalledTimes(toast === 'success' ? 1 : 0)
+ expect(infoSpy).toHaveBeenCalledTimes(toast === 'info' ? 1 : 0)
+ expect(warningSpy).toHaveBeenCalledTimes(toast === 'warning' ? 1 : 0)
+ })
})
diff --git a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
index 3961aff3a2df..baa7ac87ff7e 100644
--- a/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
+++ b/products/workflows/frontend/Workflows/batchWorkflowJobsLogic.ts
@@ -1,10 +1,14 @@
-import { MakeLogicType, kea, key, path, props, selectors } from 'kea'
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { lazyLoaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
-import api from 'lib/api'
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api, { ApiConfig } from 'lib/api'
import { urls } from 'scenes/urls'
+import { hogFlowsBatchJobsCancelCreate } from 'products/workflows/frontend/generated/api'
+
import { HogFlowBatchJob } from './hogflows/types'
export interface BatchWorkflowJobsLogicProps {
@@ -15,11 +19,18 @@ export interface BatchWorkflowJobsLogicProps {
export interface batchWorkflowJobsLogicValues {
batchWorkflowJobs: HogFlowBatchJob[] | null
batchWorkflowJobsLoading: boolean
+ cancellingJobIds: string[]
jobs: HogFlowBatchJob[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface batchWorkflowJobsLogicActions {
+ cancelBatchJob: (jobId: string) => {
+ jobId: string
+ }
+ cancelBatchJobComplete: (jobId: string) => {
+ jobId: string
+ }
loadBatchWorkflowJobs: () => any
loadBatchWorkflowJobsFailure: (
error: string,
@@ -56,6 +67,23 @@ export const batchWorkflowJobsLogic = kea<batchWorkflowJobsLogicType>([
path(['products', 'workflows', 'frontend', 'Workflows', 'batchWorkflowJobsLogic']),
props({ id: 'new' } as BatchWorkflowJobsLogicProps),
key((props) => props.id || 'new'),
+ actions({
+ cancelBatchJob: (jobId: string) => ({ jobId }),
+ cancelBatchJobComplete: (jobId: string) => ({ jobId }),
+ }),
+ reducers({
+ // Guards the Stop button against a second request while the first is in flight: the
+ // job stays non-terminal until the flip lands and the reload returns, so the trigger
+ // stays clickable. Tracked per job id and cleared when the request settles.
+ cancellingJobIds: [
+ [] as string[],
+ {
+ cancelBatchJob: (state: string[], { jobId }: { jobId: string }) => [...new Set([...state, jobId])],
+ cancelBatchJobComplete: (state: string[], { jobId }: { jobId: string }) =>
+ state.filter((id) => id !== jobId),
+ },
+ ],
+ }),
lazyLoaders(({ props }) => ({
batchWorkflowJobs: [
null as HogFlowBatchJob[] | null,
@@ -70,6 +98,36 @@ export const batchWorkflowJobsLogic = kea<batchWorkflowJobsLogicType>([
},
],
})),
+ listeners(({ props, actions }) => ({
+ cancelBatchJob: async ({ jobId }) => {
+ if (!props.id || props.id === 'new') {
+ actions.cancelBatchJobComplete(jobId)
+ return
+ }
+
+ const teamId = ApiConfig.getCurrentTeamId()
+ try {
+ const response = await hogFlowsBatchJobsCancelCreate(String(teamId), props.id, jobId)
+ if (!response.done) {
+ // One request flags a bounded batch of runs, so a very large run leaves
+ // some in flight. Prompt another pass instead of reporting a clean stop.
+ lemonToast.warning('Some runs are still in flight. Select Stop again to catch the rest.')
+ } else if (response.status === 'cancelled') {
+ lemonToast.success('Batch run stopped. Runs still in flight are being canceled.')
+ } else {
+ // done:true with a non-cancelled status means the run reached a terminal state
+ // (completed or failed) before the stop could flag anything — the backend reports
+ // that instead of flipping to cancelled, so don't claim a stop that didn't happen.
+ lemonToast.info('This batch run already finished, so there was nothing to stop.')
+ }
+ actions.loadBatchWorkflowJobs()
+ } catch (e: any) {
+ lemonToast.error(`Failed to stop the batch run: ${e?.detail ?? e?.message ?? String(e)}`)
+ } finally {
+ actions.cancelBatchJobComplete(jobId)
+ }
+ },
+ })),
selectors({
jobs: [(s) => [s.batchWorkflowJobs], (batchWorkflowJobs: HogFlowBatchJob[] | null) => batchWorkflowJobs || []],
}),
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 0fe7f1e2a6c6..b72ef88f06fd 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -796,6 +796,29 @@ export interface HogFlowBatchJobApi {
readonly updated_at: string
}
+/**
+ * Response from the batch job cancel endpoint. Stopping is asynchronous: this call flags the
+ * run's audience fan-out and its in-flight child runs, and the workflow workers terminate
+ * them shortly after. Messages already sent are not recalled.
+ */
+export interface HogFlowBatchJobCancelResponseApi {
+ /** The batch run's status after this request. 'cancelled' once every in-flight run is flagged; a completion that raced the stop wins and is reported instead.
+ *
+ * * `waiting` - Waiting
+ * * `queued` - Queued
+ * * `active` - Active
+ * * `completed` - Completed
+ * * `cancelled` - Cancelled
+ * * `failed` - Failed */
+ status: HogFlowBatchJobStatusEnumApi
+ /** In-flight runs newly flagged for cancellation by this request. */
+ marked: number
+ /** In-flight runs of this batch not yet flagged. Non-zero on very large runs; call again. */
+ remaining: number
+ /** True when no in-flight runs of this batch remain unflagged. */
+ done: boolean
+}
+
/**
* * `update_action` - update_action
* * `add_action` - add_action
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 5c95dcc30310..885b46394ab5 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -16,6 +16,7 @@ import type {
EmailSendingSuspensionStatusApi,
HogFlowApi,
HogFlowBatchJobApi,
+ HogFlowBatchJobCancelResponseApi,
HogFlowInvocationApi,
HogFlowPublishRequestApi,
HogFlowPublishResponseApi,
@@ -445,6 +446,33 @@ export const hogFlowsBatchJobsCreate = async (
})
}
+export const getHogFlowsBatchJobsCancelCreateUrl = (projectId: string, id: string, batchJobId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/batch_jobs/${batchJobId}/cancel/`
+}
+
+/**
+ * Stop a batch run: no more of its audience is enrolled, and every run of it
+ * still in flight is canceled.
+ *
+ * Stopping is asynchronous: runs are flagged here, then terminated by the
+ * workflow workers. Steps that already executed, like sent messages, are not
+ * undone. Already-finished batch runs are left untouched.
+ */
+export const hogFlowsBatchJobsCancelCreate = async (
+ projectId: string,
+ id: string,
+ batchJobId: string,
+ options?: RequestInit
+): Promise<HogFlowBatchJobCancelResponseApi> => {
+ return apiMutator<HogFlowBatchJobCancelResponseApi>(
+ getHogFlowsBatchJobsCancelCreateUrl(projectId, id, batchJobId),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
export const getHogFlowsDiscardDraftCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/discard_draft/`
}
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 282a2ac7f5e0..d400329d44c3 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -42,6 +42,9 @@ tools:
hog-flows-assets-retrieve:
operation: hog_flows_assets_retrieve
enabled: false
+ hog-flows-batch-jobs-cancel-create:
+ operation: hog_flows_batch_jobs_cancel_create
+ enabled: false
hog-flows-batch-jobs-create:
operation: hog_flows_batch_jobs_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 42de5720f963..27cb86a3e56b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39133,6 +39133,29 @@ export namespace Schemas {
readonly updated_at: string;
}
+ /**
+ * Response from the batch job cancel endpoint. Stopping is asynchronous: this call flags the
+ * run's audience fan-out and its in-flight child runs, and the workflow workers terminate
+ * them shortly after. Messages already sent are not recalled.
+ */
+ export interface HogFlowBatchJobCancelResponse {
+ /** The batch run's status after this request. 'cancelled' once every in-flight run is flagged; a completion that raced the stop wins and is reported instead.
+ *
+ * * `waiting` - Waiting
+ * * `queued` - Queued
+ * * `active` - Active
+ * * `completed` - Completed
+ * * `cancelled` - Cancelled
+ * * `failed` - Failed */
+ status: HogFlowBatchJobStatusEnum;
+ /** In-flight runs newly flagged for cancellation by this request. */
+ marked: number;
+ /** In-flight runs of this batch not yet flagged. Non-zero on very large runs; call again. */
+ remaining: number;
+ /** True when no in-flight runs of this batch remain unflagged. */
+ done: boolean;
+ }
+
/**
* * `update_action` - update_action
* * `add_action` - add_action