Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(workflows): enforce per-team audience cap for batch workflows (#65515)

Meikel Ratz0ee97f48f20e
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index b8788cb575dd..40c9fdbfa05b 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -765,6 +765,9 @@ export class CdpApi {
return res.status(400).json({ error: 'Only batch Workflows are supported for batch jobs' })
}
+ const maxAudienceSize =
+ typeof req.body.max_audience_size === 'number' ? req.body.max_audience_size : undefined
+
const batchHogFlowRequest = {
teamId: team.id,
hogFlowId: hogFlow.id,
@@ -773,6 +776,7 @@ export class CdpApi {
properties: hogFlow.trigger.filters.properties || [],
filter_test_accounts: req.body.filters?.filter_test_accounts || false,
},
+ maxAudienceSize,
}
await this.outputs.produce(BATCH_HOGFLOW_REQUESTS_OUTPUT, {
diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts
index eb10c5a2337a..75b8d160c22e 100644
--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts
@@ -438,6 +438,121 @@ describe('CdpBatchHogFlowRequestsConsumer', () => {
expect(result.map((item) => (item as any).person?.id)).toEqual(['person-1', 'person-2'])
})
+ it('should let a request-level maxAudienceSize override the global config cap', async () => {
+ const hogFlow = await insertHogFlow(
+ new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withSimpleWorkflow({
+ trigger: {
+ type: 'batch',
+ filters: { properties: [] },
+ },
+ })
+ .build()
+ )
+
+ // Global cap is low, but this team's elevated per-team limit rides on the request.
+ processor['config'] = { ...processor['config'], CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 3 }
+
+ const mockGetBlastRadiusPersons = jest
+ .fn()
+ .mockResolvedValueOnce({
+ users_affected: ['person-1', 'person-2'],
+ cursor: 'cursor-1',
+ has_more: true,
+ })
+ .mockResolvedValueOnce({
+ users_affected: ['person-3', 'person-4'],
+ cursor: 'cursor-2',
+ has_more: true,
+ })
+ .mockResolvedValueOnce({
+ users_affected: ['person-5'],
+ cursor: null,
+ has_more: false,
+ })
+
+ processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons
+
+ const batchRequest: BatchHogFlowRequest = {
+ teamId: team.id,
+ hogFlowId: hogFlow.id,
+ parentRunId: new UUIDT().toString(),
+ maxAudienceSize: 50000,
+ filters: {
+ properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],
+ },
+ }
+
+ const result = await processor['createHogFlowInvocations']({
+ batchHogFlowRequest: batchRequest,
+ team,
+ hogFlow,
+ })
+
+ // All three pages are consumed despite the global cap of 3, and every person is queued.
+ expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(3)
+ expect(result).toHaveLength(5)
+ expect(result.map((item) => (item as any).person?.id)).toEqual([
+ 'person-1',
+ 'person-2',
+ 'person-3',
+ 'person-4',
+ 'person-5',
+ ])
+ })
+
+ it('should fall back to the global config cap when the request has no maxAudienceSize', async () => {
+ const hogFlow = await insertHogFlow(
+ new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withSimpleWorkflow({
+ trigger: {
+ type: 'batch',
+ filters: { properties: [] },
+ },
+ })
+ .build()
+ )
+
+ processor['config'] = { ...processor['config'], CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE: 3 }
+
+ const mockGetBlastRadiusPersons = jest
+ .fn()
+ .mockResolvedValueOnce({
+ users_affected: ['person-1', 'person-2'],
+ cursor: 'cursor-1',
+ has_more: true,
+ })
+ .mockResolvedValueOnce({
+ users_affected: ['person-3', 'person-4'],
+ cursor: 'cursor-2',
+ has_more: true,
+ })
+
+ processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = mockGetBlastRadiusPersons
+
+ const batchRequest: BatchHogFlowRequest = {
+ teamId: team.id,
+ hogFlowId: hogFlow.id,
+ parentRunId: new UUIDT().toString(),
+ filters: {
+ properties: [{ key: 'email', value: '[email protected]', operator: 'exact', type: 'person' }],
+ },
+ }
+
+ const result = await processor['createHogFlowInvocations']({
+ batchHogFlowRequest: batchRequest,
+ team,
+ hogFlow,
+ })
+
+ // Stops after the 2nd page (4 > 3), same as the global-cap behavior.
+ expect(mockGetBlastRadiusPersons).toHaveBeenCalledTimes(2)
+ expect(result).toHaveLength(2)
+ expect(result.map((item) => (item as any).person?.id)).toEqual(['person-1', 'person-2'])
+ })
+
it('should include default variables from hogFlow', async () => {
const hogFlow = await insertHogFlow(
new FixtureHogFlowBuilder()
diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
index 866894320771..2bfbd1c3eab5 100644
--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts
@@ -25,6 +25,9 @@ export interface BatchHogFlowRequest {
parentRunId: string
filters: Pick<HogFunctionFilters, 'properties' | 'filter_test_accounts'>
group_type_index?: number
+ // Per-team audience cap resolved on the Django side (HOGFLOW_BATCH_TRIGGER_LIMIT). When absent,
+ // we fall back to the global CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE config default.
+ maxAudienceSize?: number
}
export interface BatchHogFlowRequestMessage {
@@ -129,6 +132,7 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServ
const allInvocations: CyclotronJobInvocation[] = []
let cursor: string | null = null
let totalPersonsProcessed = 0
+ const maxAudienceSize = batchHogFlowRequest.maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE
try {
// Fetch persons in batches using cursor-based pagination
@@ -148,10 +152,10 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServ
const batchPersonsCount = blastRadiusPersons.users_affected.length
totalPersonsProcessed += batchPersonsCount
- if (totalPersonsProcessed > this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE) {
+ if (totalPersonsProcessed > maxAudienceSize) {
logger.warn(
'⚠️',
- `Batch HogFlow run ${batchHogFlowRequest.parentRunId} has exceeded the maximum audience size of ${this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE}. Stopping further processing.`,
+ `Batch HogFlow run ${batchHogFlowRequest.parentRunId} has exceeded the maximum audience size of ${maxAudienceSize}. Stopping further processing.`,
{ totalPersonsProcessed, batchHogFlowRequest }
)
break
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index a21e179f28a0..9a0782b2543a 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -148,9 +148,12 @@ def get_hog_function_templates() -> requests.Response:
)
-def create_batch_hog_flow_job_invocation(team_id: int, hog_flow_id: UUIDT, batch_job_id: UUIDT) -> requests.Response:
+def create_batch_hog_flow_job_invocation(
+ team_id: int, hog_flow_id: UUIDT, batch_job_id: UUIDT, max_audience_size: int | None = None
+) -> requests.Response:
return internal_requests.post(
CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/batch_invocations/{batch_job_id}",
+ json={"max_audience_size": max_audience_size},
headers=get_internal_api_headers(),
)
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 555daed819fd..5fd6f24b3adb 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -2181,6 +2181,7 @@ class TestHogFlowAPI(APIBaseTest):
assert "delay" in action_types # Delay is present
assert action_types.count("function") == 2 # Two function actions
+ @override_settings(HOGFLOW_BATCH_TRIGGER_LIMIT=5000, HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS=set())
@patch(
"products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
)
@@ -2198,6 +2199,27 @@ class TestHogFlowAPI(APIBaseTest):
assert response.json()["variables"] == batch_job_data["variables"]
assert response.json()["status"] == "queued"
mock_create_invocation.assert_called_once()
+ # The per-team audience cap must ride on the invocation so the consumer enforces the team's limit.
+ assert mock_create_invocation.call_args.kwargs["max_audience_size"] == 5000
+
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_post_hog_flow_batch_jobs_passes_elevated_audience_size(self, mock_create_invocation):
+ flow_id = self._create_active_hog_flow()
+
+ with override_settings(
+ HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED=50000,
+ HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS={self.team.id},
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",
+ {"variables": [{"key": "first_name", "value": "Test"}]},
+ )
+
+ assert response.status_code == 200, response.json()
+ mock_create_invocation.assert_called_once()
+ assert mock_create_invocation.call_args.kwargs["max_audience_size"] == 50000
def test_post_hog_flow_batch_jobs_endpoint_rejects_non_active_workflow(self):
# A batch run is gated on an enabled workflow — a draft (or archived) one can't start a broadcast.
diff --git a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
index 76623d93708e..31d521d7f6c1 100644
--- a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
+++ b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
@@ -7,6 +7,8 @@ import structlog
from posthog.models.utils import RootTeamMixin, UUIDTModel
from posthog.plugins.plugin_server_api import create_batch_hog_flow_job_invocation
+from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit
+
logger = structlog.get_logger(__name__)
@@ -47,7 +49,10 @@ def handle_hog_flow_batch_job_created(sender, instance, created, **kwargs):
if created:
try:
create_batch_hog_flow_job_invocation(
- team_id=instance.team.id, hog_flow_id=instance.hog_flow.id, batch_job_id=instance.id
+ team_id=instance.team.id,
+ hog_flow_id=instance.hog_flow.id,
+ batch_job_id=instance.id,
+ max_audience_size=get_hogflow_batch_trigger_limit(instance.team.id),
)
except Exception as e:
logger.exception(
diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.ts
index 18f164b58eff..8e9f56738d9b 100644
--- a/services/mcp/src/tools/workflows/batch.ts
+++ b/services/mcp/src/tools/workflows/batch.ts
@@ -2,14 +2,7 @@ import { z } from 'zod'
import type { Context, ToolBase } from '@/tools/types'
-/**
- * Mirrors `CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE` in nodejs/src/cdp/config.ts — the cap the batch
- * consumer enforces by silently truncating the fan-out. We reject past it here so MCP callers get an
- * explicit error instead of an under-the-hood partial run. Keep the two values in sync.
- */
-export const BATCH_WORKFLOW_MAX_AUDIENCE_SIZE = 5000
-
-type BlastRadius = { affected: number; total: number }
+type BlastRadius = { affected: number; total: number; limit: number }
type WorkflowTrigger = { type?: string; filters?: unknown }
@@ -39,18 +32,20 @@ async function sizeAudience(context: Context, projectId: string, filters: unknow
/**
* Echo-back guard: the caller must have sized the audience with workflows-blast-radius and surfaced the
- * number to the user. We recompute it here and reject on drift or over-cap before any fan-out.
+ * number to the user. We recompute it here and reject on drift or over-cap before any fan-out. The cap is
+ * the per-team `limit` the blast-radius endpoint returns (HOGFLOW_BATCH_TRIGGER_LIMIT), which the batch
+ * consumer also enforces — so the run is rejected here rather than silently truncated downstream.
*/
-function assertAcknowledged(affected: number, acknowledged: number): void {
+function assertAcknowledged(affected: number, acknowledged: number, limit: number): void {
if (affected !== acknowledged) {
throw new Error(
`Audience size is now ${affected} users (you acknowledged ${acknowledged}). Re-check with ` +
`workflows-blast-radius and confirm the new count with the user before running.`
)
}
- if (affected > BATCH_WORKFLOW_MAX_AUDIENCE_SIZE) {
+ if (affected > limit) {
throw new Error(
- `Audience of ${affected} users exceeds the ${BATCH_WORKFLOW_MAX_AUDIENCE_SIZE}-user cap. Narrow the ` +
+ `Audience of ${affected} users exceeds the ${limit}-user cap for this project. Narrow the ` +
`workflow's batch trigger filters to reduce the audience, then try again.`
)
}
@@ -108,8 +103,8 @@ export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> =>
}
const filters = triggerFilters(trigger)
- const { affected } = await sizeAudience(context, projectId, filters)
- assertAcknowledged(affected, params.acknowledged_affected_count)
+ const { affected, limit } = await sizeAudience(context, projectId, filters)
+ assertAcknowledged(affected, params.acknowledged_affected_count, limit)
return await context.api.request({
method: 'POST',
@@ -165,8 +160,8 @@ export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema,
)
}
- const { affected } = await sizeAudience(context, projectId, triggerFilters(trigger))
- assertAcknowledged(affected, params.acknowledged_affected_count)
+ const { affected, limit } = await sizeAudience(context, projectId, triggerFilters(trigger))
+ assertAcknowledged(affected, params.acknowledged_affected_count, limit)
return await context.api.request({
method: 'POST',
diff --git a/services/mcp/tests/unit/workflows-batch-handlers.test.ts b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
index 66b77af9681d..e843149a5ab9 100644
--- a/services/mcp/tests/unit/workflows-batch-handlers.test.ts
+++ b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
@@ -1,12 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Context } from '@/tools/types'
-import {
- BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,
- workflowsBlastRadius,
- workflowsRunBatch,
- workflowsScheduleCreate,
-} from '@/tools/workflows/batch'
+import { workflowsBlastRadius, workflowsRunBatch, workflowsScheduleCreate } from '@/tools/workflows/batch'
+
+// Default per-team audience cap the mocked blast-radius endpoint returns unless a test overrides it.
+const DEFAULT_LIMIT = 50_000
interface RequestArgs {
method: string
@@ -24,7 +22,7 @@ const BATCH_FILTERS = { properties: [{ key: 'email', value: 'is_set', type: 'per
*/
function createMockContext(opts: {
trigger: unknown
- blastRadius: { affected: number; total: number }
+ blastRadius: { affected: number; total: number; limit?: number }
status?: string
}): { context: Context; request: ReturnType<typeof vi.fn> } {
const request = vi.fn(async ({ method, path }: RequestArgs) => {
@@ -32,7 +30,7 @@ function createMockContext(opts: {
return { id: 'wf-1', status: opts.status ?? 'active', trigger: opts.trigger }
}
if (method === 'POST' && path.endsWith('/user_blast_radius/')) {
- return opts.blastRadius
+ return { limit: DEFAULT_LIMIT, ...opts.blastRadius }
}
if (method === 'POST' && path.endsWith('/batch_jobs/')) {
return { id: 'batch-1', status: 'queued' }
@@ -80,7 +78,7 @@ describe('workflows batch handlers', () => {
path: '/api/projects/1/hog_flows/user_blast_radius/',
body: { filters: BATCH_FILTERS },
})
- expect(result).toEqual({ affected: 42, total: 100 })
+ expect(result).toEqual({ affected: 42, total: 100, limit: DEFAULT_LIMIT })
})
})
@@ -130,21 +128,36 @@ describe('workflows batch handlers', () => {
expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
})
- it('rejects and does not fire when the audience exceeds the cap', async () => {
+ it('rejects and does not fire when the audience exceeds the per-team cap', async () => {
const { context, request } = createMockContext({
trigger: { type: 'batch', filters: BATCH_FILTERS },
- blastRadius: { affected: BATCH_WORKFLOW_MAX_AUDIENCE_SIZE + 1, total: 1_000_000 },
+ blastRadius: { affected: 5001, total: 1_000_000, limit: 5000 },
})
await expect(
runBatchTool.handler(context, {
workflow_id: 'wf-1',
- acknowledged_affected_count: BATCH_WORKFLOW_MAX_AUDIENCE_SIZE + 1,
+ acknowledged_affected_count: 5001,
})
- ).rejects.toThrow(new RegExp(String(BATCH_WORKFLOW_MAX_AUDIENCE_SIZE)))
+ ).rejects.toThrow(/5000/)
expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
})
+ it('fires for a large audience that is within an elevated per-team cap', async () => {
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 40_000, total: 1_000_000, limit: 50_000 },
+ })
+
+ const result = await runBatchTool.handler(context, {
+ workflow_id: 'wf-1',
+ acknowledged_affected_count: 40_000,
+ })
+
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(true)
+ expect(result).toMatchObject({ id: 'batch-1' })
+ })
+
it('rejects workflows whose trigger is not a batch trigger', async () => {
const { context, request } = createMockContext({
trigger: { type: 'event', filters: BATCH_FILTERS },