: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): account audience for the batch trigger (#76808)
Arthur Moreira de Deus80e0a4a8348d
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex cdd114be6770..43a91da3903b 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -1122,6 +1122,7 @@ export class CdpApi {throw new Error('Batch resolver producer is not configured (missing CYCLOTRON_NODE_DATABASE_URL)')}+ const audienceType = req.body.filters?.audience_type ?? hogFlow.trigger.filters.audience_typeconst initialState: BatchResolverState = {batchJobId: parent_run_id,teamId: team.id,@@ -1130,10 +1131,16 @@ export class CdpApi {// Prefer the audience snapshot validated at dispatch time - re-reading the live// trigger here would let an edit landing after the confirm check widen the send.// Fallback covers callers that predate the snapshot.+ audience_type: audienceType,properties: req.body.filters?.properties ?? (hogFlow.trigger.filters.properties || []),filter_test_accounts:req.body.filters?.filter_test_accounts ??(hogFlow.trigger.filters.filter_test_accounts || false),+ tag_names: req.body.filters?.tag_names ?? hogFlow.trigger.filters.tag_names,+ assigned_to_user_ids:+ req.body.filters?.assigned_to_user_ids ?? hogFlow.trigger.filters.assigned_to_user_ids,+ all_roles_unassigned:+ req.body.filters?.all_roles_unassigned ?? hogFlow.trigger.filters.all_roles_unassigned,},variables: req.body.variables ?? {},groupTypeIndex: typeof req.body.group_type_index === 'number' ? req.body.group_type_index : undefined,@@ -1141,7 +1148,8 @@ export class CdpApi {// `{{ person.properties.email }}`. Custom recipients (work_email, computed Liquid, static// strings) would make the dedupe key diverge from the actual send target — better to skip// dedupe than dedupe wrongly. Also skip when the flow has no email action at all.- dedupeKey: canDedupeByEmail(hogFlow) ? ('email' as const) : undefined,+ // Account audiences carry no person (and external ids are already unique), so never dedupe.+ dedupeKey: audienceType !== 'accounts' && canDedupeByEmail(hogFlow) ? ('email' as const) : undefined,maxAudienceSize: maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,cursor: null,totalEnqueued: 0,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.tsnew file mode 100644index 000000000000..5f75d23585eb--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts@@ -0,0 +1,36 @@+import { Team } from '~/types'++import { CyclotronJobInvocationHogFlow } from '../types'+import { buildAccountHogFlowInvocation } from './cdp-cyclotron-worker-batch-resolve.consumer'++describe('buildAccountHogFlowInvocation', () => {+ const team = { id: 123, name: 'Test team' } as Team++ it('carries the account group key and no person', () => {+ const invocation = buildAccountHogFlowInvocation({+ siteUrl: 'https://us.posthog.com',+ parentRunId: 'batch-job-1',+ team,+ hogFlowId: 'flow-1',+ externalId: 'acme-1',+ groupType: 'customer',+ defaultVariables: { greeting: 'hi' },+ })++ const state = invocation.state as CyclotronJobInvocationHogFlow['state']++ expect(state.event.event).toEqual('$batch_hog_flow_invocation')+ // distinct_id doubles as the per-account key for invocation_results; it must NOT+ // resolve to a person (the hogflow worker skips the lookup for account audiences).+ expect(state.event.distinct_id).toEqual('acme-1')+ expect(state.event.properties['$groups']).toEqual({ customer: 'acme-1' })+ expect(state.personId).toBeUndefined()+ // The stamp is what the hogflow worker trusts when the live trigger has been+ // edited to a person audience while these children were still queued.+ expect(state.accountAudience).toBe(true)+ expect(state.variables).toEqual({ greeting: 'hi' })+ expect(invocation.parentRunId).toEqual('batch-job-1')+ expect(invocation.queue).toEqual('hogflow')+ expect((invocation as any).person).toBeUndefined()+ })+})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.tsindex 592321cc56a7..2aea5d78d540 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@@ -18,7 +18,11 @@ import {import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'import { invocationToV2JobInit } from '../services/job-queue/job-queue-postgres-v2'import { CyclotronJobInvocation } from '../types'-import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals, logEntry } from '../utils'+import {+ convertAccountBatchHogFlowRequestToHogFunctionInvocationGlobals,+ convertBatchHogFlowRequestToHogFunctionInvocationGlobals,+ logEntry,+} from '../utils'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterBatchHogFlowTriggerFailed } from './metrics'@@ -187,17 +191,33 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServereturn}- let page+ const isAccountAudience = state.filters.audience_type === 'accounts'++ // Normalized page shape so budget/truncation/state logic below stays single-path.+ let page: { ids: string[]; cursor: string | null; has_more: boolean; accountGroupType?: string }try {- page = await instrumentFn('cdpBatchResolve.getBlastRadiusPersons', () =>- this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(- team,- state.filters,- state.groupTypeIndex,- state.cursor,- state.dedupeKey+ if (isAccountAudience) {+ const accountPage = await instrumentFn('cdpBatchResolve.getAccountAudiencePage', () =>+ this.hogFlowBatchPersonQueryService.getAccountAudiencePage(team, state.filters, state.cursor))- )+ page = {+ ids: accountPage.accounts,+ cursor: accountPage.cursor,+ has_more: accountPage.has_more,+ accountGroupType: accountPage.group_type,+ }+ } else {+ const personsPage = await instrumentFn('cdpBatchResolve.getBlastRadiusPersons', () =>+ this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(+ team,+ state.filters,+ state.groupTypeIndex,+ state.cursor,+ state.dedupeKey+ )+ )+ page = { ids: personsPage.users_affected, cursor: personsPage.cursor, has_more: personsPage.has_more }+ }} catch (err) {counterBatchHogFlowResolverPagesProcessed.labels({ outcome: 'fetch_failure' }).inc()const nextAttempts = state.attempts + 1@@ -239,20 +259,30 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe// up to one full page's worth of children before the next dequeue// notices and stops.const remainingBudget = Math.max(0, state.maxAudienceSize - state.totalEnqueued)- const eligibleUsers = page.users_affected.slice(0, remainingBudget)- const pageTruncated = eligibleUsers.length < page.users_affected.length+ const eligibleIds = page.ids.slice(0, remainingBudget)+ const pageTruncated = eligibleIds.length < page.ids.lengthconst defaultVariables = mergeDefaultVariables(hogFlow.variables, state.variables)- const children: CyclotronV2JobInit[] = eligibleUsers.map((personId) =>+ const children: CyclotronV2JobInit[] = eligibleIds.map((id) =>invocationToV2JobInit(- buildHogFlowInvocation({- siteUrl: this.config.SITE_URL,- parentRunId: state.batchJobId,- team,- hogFlowId: hogFlow.id,- personId,- defaultVariables,- })+ isAccountAudience+ ? buildAccountHogFlowInvocation({+ siteUrl: this.config.SITE_URL,+ parentRunId: state.batchJobId,+ team,+ hogFlowId: hogFlow.id,+ externalId: id,+ groupType: page.accountGroupType ?? '',+ defaultVariables,+ })+ : buildHogFlowInvocation({+ siteUrl: this.config.SITE_URL,+ parentRunId: state.batchJobId,+ team,+ hogFlowId: hogFlow.id,+ personId: id,+ defaultVariables,+ })))@@ -284,7 +314,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServelogger.info('📝',- `${this.name} - processed page for batch ${state.batchJobId}: ${children.length} persons (${newState.totalEnqueued} total, ${newState.pagesProcessed} pages)`+ `${this.name} - processed page for batch ${state.batchJobId}: ${children.length} ${isAccountAudience ? 'accounts' : 'persons'} (${newState.totalEnqueued} total, ${newState.pagesProcessed} pages)`)}@@ -434,6 +464,45 @@ function mergeDefaultVariables(return { ...defaults, ...runOverrides }}+// Mirrors buildHogFlowInvocation for an account audience: the invocation carries the+// account's group key (via $groups and distinct_id) and no person at all — the hogflow+// worker skips person resolution for account audiences.+export function buildAccountHogFlowInvocation(params: {+ siteUrl: string+ parentRunId: string+ team: Team+ hogFlowId: string+ externalId: string+ groupType: string+ defaultVariables: Record<string, unknown>+}): CyclotronJobInvocation {+ const invocationGlobals = convertAccountBatchHogFlowRequestToHogFunctionInvocationGlobals({+ team: params.team,+ externalId: params.externalId,+ groupType: params.groupType,+ siteUrl: params.siteUrl,+ })++ const filterGlobals = convertToHogFunctionFilterGlobal(invocationGlobals)++ return {+ id: new UUIDT().toString(),+ state: {+ event: invocationGlobals.event,+ accountAudience: true,+ actionStepCount: 0,+ variables: params.defaultVariables,+ } as any,+ teamId: params.team.id,+ functionId: params.hogFlowId,+ parentRunId: params.parentRunId,+ filterGlobals,+ queue: 'hogflow' as const,+ queuePriority: 1,+ queueScheduledAt: DateTime.now(),+ } as CyclotronJobInvocation+}+// Mirrors `createHogFlowInvocation` from the legacy Kafka consumer so children// land in cyclotron_jobs looking the same regardless of dispatch path.function buildHogFlowInvocation(params: {diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex 304fd5d1338c..b47c0b73dd3f 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -62,6 +62,15 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {// rather than relying on event.distinct_id being empty so future changes to the// synthetic event shape don't accidentally re-enable the lookup.const isWarehouseRow = hogFlow.trigger?.type === 'data-warehouse-table'+ // Account-audience batch invocations carry the account's group key as+ // event.distinct_id; resolving it as a person distinct_id would attach an+ // unrelated person to the run. Accounts have no person — skip the lookup.+ // The state stamp wins over the live trigger, which may have been edited to a+ // person audience while these children were queued; the trigger check remains+ // as a fallback for jobs enqueued before the stamp existed.+ const isAccountAudience =+ hogFlowInvocationState.accountAudience === true ||+ (hogFlow.trigger?.type === 'batch' && hogFlow.trigger.filters?.audience_type === 'accounts')// A person merge repointed this job's distinct_id and re-keyed personId onto the survivor.// Resolve by that personId so the step reads the merged person — resolving by the repointed// distinct_id would hit its stale ~1min cache entry (the pre-merge person) and e.g. drop an email.@@ -73,11 +82,12 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {if (resolveByRepointedPerson) {delete hogFlowInvocationState.personIdRepointed}- const personIdOrDistinctId = isWarehouseRow- ? undefined- : resolveByRepointedPerson- ? hogFlowInvocationState.personId- : hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personId+ const personIdOrDistinctId =+ isWarehouseRow || isAccountAudience+ ? undefined+ : resolveByRepointedPerson+ ? hogFlowInvocationState.personId+ : hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personIdconst kind =resolveByRepointedPerson || !hogFlowInvocationState.event.distinct_id ? 'person_id' : 'distinct_id'diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex c62f04e6f67e..4b3d25e5cec4 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -65,8 +65,13 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [z.object({type: z.literal('batch'),filters: z.object({+ // 'accounts' fans out one run per customer analytics account instead of per person+ audience_type: z.enum(['persons', 'accounts']).optional(),properties: z.array(z.any()),filter_test_accounts: z.boolean().optional(),+ tag_names: z.array(z.string()).optional(),+ assigned_to_user_ids: z.array(z.number()).optional(),+ all_roles_unassigned: z.boolean().optional(),}),}),z.object({diff --git a/nodejs/src/cdp/services/hogflows/batch-resolver.types.test.ts b/nodejs/src/cdp/services/hogflows/batch-resolver.types.test.tsnew file mode 100644index 000000000000..05d61e3a16c9--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/batch-resolver.types.test.ts@@ -0,0 +1,27 @@+import { deserializeResolverState, serializeResolverState } from './batch-resolver.types'++describe('BatchResolverState serialization', () => {+ it('round-trips account audience filters (zod strips unknown keys, so a missed schema field would vanish)', () => {+ const state = {+ batchJobId: 'job-1',+ teamId: 1,+ hogFlowId: 'flow-1',+ filters: {+ audience_type: 'accounts' as const,+ properties: [{ key: 'defn-id', type: 'account_custom_property', operator: 'exact', value: ['x'] }],+ tag_names: ['vip'],+ assigned_to_user_ids: [7],+ all_roles_unassigned: true,+ },+ variables: {},+ maxAudienceSize: 100,+ cursor: null,+ totalEnqueued: 0,+ pagesProcessed: 0,+ attempts: 0,+ startedAt: '2026-01-01T00:00:00.000Z',+ }++ expect(deserializeResolverState(serializeResolverState(state))).toEqual(state)+ })+})diff --git a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts b/nodejs/src/cdp/services/hogflows/batch-resolver.types.tsindex 00c77b32ae7b..6e145eba880e 100644--- a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts+++ b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts@@ -19,10 +19,17 @@ export const BatchResolverStateSchema = z.object({teamId: z.number().int(),hogFlowId: z.string().min(1),filters: z.object({+ // 'accounts' switches the resolver to page customer analytics accounts+ // (external ids) instead of persons. Frozen here like the rest of the+ // audience so a mid-run trigger edit can't change what a page fans out to.+ audience_type: z.enum(['persons', 'accounts']).optional(),// Each property entry is an arbitrary record — keep loose so resolver// replays survive new filter-property fields the worker doesn't read.properties: z.array(z.record(z.string(), z.any())).optional(),filter_test_accounts: z.boolean().optional(),+ tag_names: z.array(z.string()).optional(),+ assigned_to_user_ids: z.array(z.number()).optional(),+ all_roles_unassigned: z.boolean().optional(),}),variables: z.record(z.string(), z.unknown()),groupTypeIndex: z.number().int().optional(),diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.tsindex c731b483e5be..a549be0ac9f5 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts@@ -1,6 +1,7 @@import { Team } from '~/types'import {+ AccountAudienceResponse,BlastRadiusPersonsResponse,BlastRadiusResponse,HogFlowBatchPersonQueryService,@@ -215,4 +216,49 @@ describe('HogFlowBatchPersonQueryService', () => {await expect(service.getBlastRadiusPersons(team, filters)).rejects.toThrow('timeout')})})++ describe('getAccountAudiencePage', () => {+ const accountFilters = { audience_type: 'accounts', properties: [], tag_names: ['vip'] }++ it('calls the Django endpoint and returns parsed response', async () => {+ const service = createService()+ const response: AccountAudienceResponse = {+ accounts: ['acme', 'globex'],+ cursor: 'globex',+ has_more: false,+ group_type: 'customer',+ }++ fetchMock.mockResolvedValue({+ fetchResponse: createFetchResponse(200, response),+ fetchError: null,+ })++ await expect(service.getAccountAudiencePage(team, accountFilters, 'abc')).resolves.toEqual(response)++ expect(fetchMock).toHaveBeenCalledWith({+ urlPath: '/api/projects/123/internal/hog_flows/account_audience',+ fetchParams: {+ method: 'POST',+ body: JSON.stringify({+ filters: accountFilters,+ cursor: 'abc',+ }),+ },+ })+ })++ it('throws when the endpoint responds with non-200 status', async () => {+ const service = createService()++ fetchMock.mockResolvedValue({+ fetchResponse: createFetchResponse(400, 'bad filters'),+ fetchError: null,+ })++ await expect(service.getAccountAudiencePage(team, accountFilters)).rejects.toThrow(+ 'Failed to fetch account audience: 400 bad filters'+ )+ })+ })})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.tsindex 6ffbf9c93c75..a8b2baef40fc 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts@@ -16,6 +16,13 @@ export interface BlastRadiusPersonsResponse {has_more: boolean}+export interface AccountAudienceResponse {+ accounts: Array<string>+ cursor: string | null+ has_more: boolean+ group_type: string+}+/*** Service for querying persons via Django internal API for batch HogFlow processing.* Calls internal endpoints authenticated with INTERNAL_API_SECRET.@@ -129,4 +136,53 @@ export class HogFlowBatchPersonQueryService {throw error}}++ /**+ * Page a customer analytics account audience (external ids), cursor-paginated.+ */+ async getAccountAudiencePage(+ team: Team,+ filters: unknown,+ cursor?: string | null+ ): Promise<AccountAudienceResponse> {+ const urlPath = `/api/projects/${team.id}/internal/hog_flows/account_audience` as const++ try {+ const { fetchResponse, fetchError } = await this.internalFetchService.fetch({+ urlPath,+ fetchParams: {+ method: 'POST',+ body: JSON.stringify({+ filters,+ cursor: cursor || null,+ }),+ },+ })++ if (!fetchResponse || fetchError) {+ logger.error('Error fetching account audience from Django', {+ error: serializeError(fetchError),+ urlPath,+ })+ throw fetchError+ }++ if (fetchResponse.status !== 200) {+ const errorText = await fetchResponse.text()+ logger.error('Failed to fetch account audience from Django', {+ status: fetchResponse.status,+ error: errorText,+ urlPath,+ })+ throw new Error(`Failed to fetch account audience: ${fetchResponse.status} ${errorText}`)+ }++ const data = parseJSON(await fetchResponse.text()) as AccountAudienceResponse++ return data+ } catch (error) {+ logger.error('Error calling account audience endpoint', { error: serializeError(error), urlPath })+ throw error+ }+ }}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex ec72426f936f..1d38be08d29a 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -344,6 +344,10 @@ export type CyclotronJobInvocationHogFlow = CyclotronJobInvocation & {export type HogFlowInvocationContext = {event: HogFunctionInvocationGlobals['event']personId?: string // Persisted person UUID, used when distinct_id is not available (e.g. batch workflows, manual person triggers)+ // Stamped at enqueue for account-audience batch children: event.distinct_id is the account's+ // group key, not a person distinct_id. The worker must trust this over the live trigger config,+ // which can be edited to a person audience while these children are still queued.+ accountAudience?: boolean// Set by the subscription matcher when a person merge repointed this job's distinct_id and re-keyed// personId onto the survivor. Tells the worker to resolve the person by personId, not the distinct_id// (whose ~1min PersonsManager cache entry still points at the pre-merge person) — otherwise adiff --git a/nodejs/src/cdp/utils.ts b/nodejs/src/cdp/utils.tsindex ee5473143d63..104f6f28719d 100644--- a/nodejs/src/cdp/utils.ts+++ b/nodejs/src/cdp/utils.ts@@ -126,6 +126,44 @@ export function convertBatchHogFlowRequestToHogFunctionInvocationGlobals({return context}+export function convertAccountBatchHogFlowRequestToHogFunctionInvocationGlobals({+ team,+ externalId,+ groupType,+ siteUrl,+}: {+ team: Team+ externalId: string+ groupType: string+ siteUrl: string+}): HogFunctionInvocationGlobals {+ const projectUrl = `${siteUrl}/project/${team.id}`++ const context: HogFunctionInvocationGlobals = {+ project: {+ id: team.id,+ name: team.name,+ url: projectUrl,+ },+ event: {+ event: '$batch_hog_flow_invocation',+ // $groups drives the worker's group hydration, so account actions defaulting to+ // {groups.<type>.id} resolve without any account-specific plumbing.+ properties: { $groups: { [groupType]: externalId } },+ uuid: new UUIDT().toString(),+ // The account's group key doubles as the invocation's distinct_id so+ // invocation_results are filterable per account. Account runs carry no person;+ // the hogflow worker skips person resolution for account audiences.+ distinct_id: externalId,+ elements_chain: '',+ timestamp: DateTime.now().toISO(),+ url: '',+ },+ }++ return context+}+export function convertInternalEventToHogFunctionInvocationGlobals(data: CdpInternalEvent,team: Team,diff --git a/posthog/urls.py b/posthog/urls.pyindex 52492dee5513..df7813a8cb7c 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -585,6 +585,10 @@ urlpatterns = ["api/projects/<str:team_id>/internal/hog_flows/user_blast_radius_persons",csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"post": "internal_user_blast_radius_persons"})),),+ path(+ "api/projects/<str:team_id>/internal/hog_flows/account_audience",+ csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"post": "internal_account_audience"})),+ ),path("api/internal/hog_flows/process_due_schedules",csrf_exempt(hog_flow.InternalHogFlowViewSet.as_view({"post": "internal_process_due_schedules"})),diff --git a/products/customer_analytics/backend/apps.py b/products/customer_analytics/backend/apps.pyindex 64b3e0fa4e96..5b2219078262 100644--- a/products/customer_analytics/backend/apps.py+++ b/products/customer_analytics/backend/apps.py@@ -8,6 +8,37 @@ class CustomerAnalyticsConfig(AppConfig):def ready(self) -> None:self._register_person_property_hooks()+ self._register_workflows_account_audience()++ def _register_workflows_account_audience(self) -> None:+ """Give the workflows batch trigger its account-audience implementation without+ workflows importing this product (the dependency runs the other way). The query+ impls are imported lazily so HogQL stays off the django.setup() path.+ """+ from products.workflows.backend.services.account_audience import (+ AccountAudienceFilters,+ register_account_audience_provider,+ )++ class _Provider:+ def count_accounts(self, team, filters: AccountAudienceFilters) -> int:+ from products.customer_analytics.backend.facade import api # noqa: PLC0415++ return api.count_accounts_for_audience(team, filters)++ def list_account_external_ids(+ self, team, filters: AccountAudienceFilters, *, cursor: str | None, limit: int+ ) -> list[str]:+ from products.customer_analytics.backend.facade import api # noqa: PLC0415++ return api.list_account_external_ids_for_audience(team, filters, cursor=cursor, limit=limit)++ def get_account_group_type_name(self, team) -> str | None:+ from products.customer_analytics.backend.facade import api # noqa: PLC0415++ return api.get_account_group_type_name(team)++ register_account_audience_provider(_Provider())def _register_person_property_hooks(self) -> None:"""Tell the data-import pipeline which columns to stage for a schema's person-propertydiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 779366e71380..b56437607019 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -35,6 +35,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Integration, OrganizationMembership, Tagfrom posthog.models.activity_logging.activity_log import AuditableScope, Detail, Trigger, changes_between, log_activityfrom posthog.models.group.util import get_group_by_key+from posthog.models.group_type_mapping import get_group_types_for_projectfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Team@@ -124,6 +125,7 @@ if TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControlfrom products.customer_analytics.backend.models import CustomPropertyValue+ from products.workflows.backend.services.account_audience import AccountAudienceFiltersdef _to_account_properties(properties: _ModelAccountProperties) -> contracts.AccountProperties:@@ -397,6 +399,36 @@ def _account_name_from_group(team: Team, external_id: str) -> str:return str(name) if name else external_id+def get_account_group_type_name(team: Team) -> str | None:+ """The group type name accounts are keyed on, or None when customer analytics is unconfigured."""+ group_type_index = team.customer_analytics_config.account_group_type_index+ if group_type_index is None:+ return None+ group_types = get_group_types_for_project(team.project_id, caller_tag="customer_analytics/account_audience")+ for mapping in group_types:+ if mapping["group_type_index"] == group_type_index:+ return mapping["group_type"]+ return None+++def count_accounts_for_audience(team: Team, filters: "AccountAudienceFilters") -> int:+ from products.customer_analytics.backend.hogql_queries import ( # noqa: PLC0415 — keeps HogQL off the import path+ account_audience,+ )++ return account_audience.count_accounts_for_audience(team, filters)+++def list_account_external_ids_for_audience(+ team: Team, filters: "AccountAudienceFilters", *, cursor: str | None, limit: int+) -> list[str]:+ from products.customer_analytics.backend.hogql_queries import ( # noqa: PLC0415 — keeps HogQL off the import path+ account_audience,+ )++ return account_audience.list_account_external_ids_for_audience(team, filters, cursor=cursor, limit=limit)++def create_external_account(team: Team, *, external_id: str, workflow_id: str | None = None) -> tuple[contracts.ExternalAccount, bool]:diff --git a/products/customer_analytics/backend/hogql_queries/account_audience.py b/products/customer_analytics/backend/hogql_queries/account_audience.pynew file mode 100644index 000000000000..ac3b3c11f0b1--- /dev/null+++ b/products/customer_analytics/backend/hogql_queries/account_audience.py@@ -0,0 +1,271 @@+"""Account selection for workflows batch audiences: HogQL over ``system.accounts``.++The custom-property predicates mirror the frontend compiler in+``products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts``;+keep the two in sync so a trigger audience matches what the Accounts scene previews.+"""++from typing import Any, cast+from uuid import UUID++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.synthetic_user import SyntheticUser++from products.customer_analytics.backend.models import CustomPropertyDefinition, DataType+from products.workflows.backend.services.account_audience import (+ AccountAudienceCustomPropertyFilter,+ AccountAudienceFilters,+)+++class _AudiencePrincipal(SyntheticUser):+ """Service principal for audience resolution: batch dispatch runs without a request user,+ and ``system.accounts`` is hidden from principals whose scopes don't cover ``account``."""++ def readable_system_table_access_scopes(self) -> set[str]:+ return {"account"}+++def _audience_principal(team: Team) -> User:+ return cast(User, _AudiencePrincipal(team, distinct_id=f"workflows-account-audience-{team.pk}"))+++_RANGE_OPERATORS = {+ "gt": ast.CompareOperationOp.Gt,+ "gte": ast.CompareOperationOp.GtEq,+ "lt": ast.CompareOperationOp.Lt,+ "lte": ast.CompareOperationOp.LtEq,+}++_DATE_OPERATORS = {+ "is_date_exact": ast.CompareOperationOp.Eq,+ "is_date_before": ast.CompareOperationOp.Lt,+ "is_date_after": ast.CompareOperationOp.Gt,+}++_BOOLEAN_LITERALS: dict[str, list[str]] = {+ "true": ["true", "1"],+ "1": ["true", "1"],+ "false": ["false", "0"],+ "0": ["false", "0"],+}+++def list_account_external_ids_for_audience(+ team: Team, filters: AccountAudienceFilters, *, cursor: str | None, limit: int+) -> list[str]:+ where = _where_exprs(team, filters)+ if cursor is not None:+ where.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["accounts", "external_id"]),+ right=ast.Constant(value=cursor),+ )+ )+ query = ast.SelectQuery(+ select=[ast.Field(chain=["accounts", "external_id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["system", "accounts"]), alias="accounts"),+ where=ast.And(exprs=where),+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["accounts", "external_id"]), order="ASC")],+ limit=ast.Constant(value=limit),+ )+ tag_queries(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY)+ response = execute_hogql_query(query=query, team=team, user=_audience_principal(team))+ return [str(row[0]) for row in response.results or []]+++def count_accounts_for_audience(team: Team, filters: AccountAudienceFilters) -> int:+ query = ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["system", "accounts"]), alias="accounts"),+ where=ast.And(exprs=_where_exprs(team, filters)),+ )+ tag_queries(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY)+ response = execute_hogql_query(query=query, team=team, user=_audience_principal(team))+ return int(response.results[0][0]) if response.results else 0+++def _where_exprs(team: Team, filters: AccountAudienceFilters) -> list[ast.Expr]:+ where: list[ast.Expr] = [parse_expr("isNotNull(accounts.external_id) AND accounts.external_id != ''")]++ if filters.tag_names:+ subquery = parse_select(+ """+ SELECT ti.account_id+ FROM system._account_tagged_items AS ti+ INNER JOIN system.tags AS t ON t.id = ti.tag_id+ WHERE t.name IN {tag_names}+ """,+ {"tag_names": ast.Constant(value=list(filters.tag_names))},+ )+ where.append(parse_expr("accounts.id IN {subquery}", {"subquery": subquery}))++ if filters.all_roles_unassigned:+ where.append(+ parse_expr(+ "accounts.id NOT IN {subquery}",+ {+ "subquery": parse_select(+ "SELECT account_id FROM system.account_relationships"+ " WHERE isNull(ended_at) AND isNotNull(user_id)"+ )+ },+ )+ )++ if filters.assigned_to_user_ids:+ where.append(+ parse_expr(+ "accounts.id IN {subquery}",+ {+ "subquery": parse_select(+ "SELECT account_id FROM system.account_relationships"+ " WHERE isNull(ended_at) AND user_id IN {user_ids}",+ {"user_ids": ast.Constant(value=list(filters.assigned_to_user_ids))},+ )+ },+ )+ )++ if filters.custom_properties:+ definitions = {+ definition.id: definition+ for definition in CustomPropertyDefinition.objects.for_team(team.pk).filter(+ id__in=[f.definition_id for f in filters.custom_properties]+ )+ }+ for custom_property_filter in filters.custom_properties:+ definition = definitions.get(custom_property_filter.definition_id)+ # A dropped predicate would silently broaden the audience to every account,+ # so an unresolvable filter fails the resolution instead.+ if definition is None:+ raise ValueError(+ f"Audience filter references a deleted or unknown custom property "+ f"({custom_property_filter.definition_id}). Remove it from the trigger."+ )+ predicate = _custom_property_filter_expr(custom_property_filter, definition)+ if predicate is None:+ raise ValueError(+ f"Audience filter on '{definition.name}' has a value incompatible with its "+ f"{definition.display_type} type."+ )+ where.append(predicate)++ return where+++def _custom_property_filter_expr(+ filter: AccountAudienceCustomPropertyFilter, definition: CustomPropertyDefinition+) -> ast.Expr | None:+ column = _value_column(filter.definition_id)+ operator = filter.operator++ if operator == "is_set":+ return ast.Call(name="isNotNull", args=[column])+ if operator == "is_not_set":+ return ast.Call(name="isNull", args=[column])++ values = _normalize_values(filter.value)+ if not values:+ return None+ data_type = definition.data_type++ if operator in ("exact", "is_not"):+ negated = operator == "is_not"+ if data_type == DataType.NUMERIC:+ numbers = _finite_numbers(values)+ if not numbers:+ return None+ comparison = _equality(ast.Call(name="toFloatOrNull", args=[column]), numbers, negated)+ elif data_type == DataType.BOOLEAN:+ literals = sorted(+ {literal for value in values for literal in _BOOLEAN_LITERALS.get(str(value).lower(), [])}+ )+ if not literals:+ return None+ comparison = _equality(column, literals, negated)+ else:+ comparison = _equality(column, [str(value) for value in values], negated)+ return _include_unset(comparison) if negated else comparison++ if operator in ("icontains", "not_icontains"):+ any_match = ast.Or(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.ILike, left=column, right=ast.Constant(value=f"%{value}%")+ )+ for value in values+ ]+ )+ return _include_unset(ast.Not(expr=any_match)) if operator == "not_icontains" else any_match++ if operator in ("regex", "not_regex"):+ any_match = ast.Or(+ exprs=[ast.Call(name="match", args=[column, ast.Constant(value=str(value))]) for value in values]+ )+ return _include_unset(ast.Not(expr=any_match)) if operator == "not_regex" else any_match++ if operator in _RANGE_OPERATORS:+ numbers = _finite_numbers(values[:1])+ if not numbers:+ return None+ return ast.CompareOperation(+ op=_RANGE_OPERATORS[operator],+ left=ast.Call(name="toFloatOrNull", args=[column]),+ right=ast.Constant(value=numbers[0]),+ )++ if operator in _DATE_OPERATORS:+ return ast.CompareOperation(+ op=_DATE_OPERATORS[operator],+ left=ast.Call(name="parseDateTimeBestEffort", args=[column]),+ right=ast.Call(name="parseDateTimeBestEffort", args=[ast.Constant(value=str(values[0]))]),+ )++ return None+++def _value_column(definition_id: UUID) -> ast.Field:+ return ast.Field(chain=["accounts", "custom_properties", "values", str(definition_id)])+++def _normalize_values(value: Any) -> list[Any]:+ raw = value if isinstance(value, list) else [] if value is None else [value]+ return [entry for entry in raw if entry is not None and entry != ""]+++def _finite_numbers(values: list[Any]) -> list[float]:+ numbers: list[float] = []+ for value in values:+ try:+ numbers.append(float(value))+ except (TypeError, ValueError):+ continue+ return numbers+++def _equality(target: ast.Expr, values: list[Any], negated: bool) -> ast.Expr:+ if len(values) == 1:+ return ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq if negated else ast.CompareOperationOp.Eq,+ left=target,+ right=ast.Constant(value=values[0]),+ )+ return ast.CompareOperation(+ op=ast.CompareOperationOp.NotIn if negated else ast.CompareOperationOp.In,+ left=target,+ right=ast.Constant(value=values),+ )+++def _include_unset(predicate: ast.Expr) -> ast.Expr:+ # The lazy join yields NULL for accounts without a value; a bare negation would+ # drop them, but "is not X" must keep them. Mirrors the frontend's ifNull(..., true).+ return ast.Call(name="ifNull", args=[predicate, ast.Constant(value=True)])diff --git a/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.pynew file mode 100644index 000000000000..891e72b4e781--- /dev/null+++ b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py@@ -0,0 +1,159 @@+from datetime import UTC, datetime+from uuid import uuid4++from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest++from django.test import override_settings++from parameterized import parameterized++from posthog.api.tagged_item import set_tags_on_object+from posthog.models.team import Team++from products.customer_analytics.backend.facade.api import (+ count_accounts_for_audience,+ list_account_external_ids_for_audience,+)+from products.customer_analytics.backend.logic import relationships as relationships_logic+from products.customer_analytics.backend.models import AccountRelationshipDefinition, CustomPropertyValue+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition+from products.workflows.backend.services.account_audience import (+ AccountAudienceCustomPropertyFilter,+ AccountAudienceFilters,+)+++@override_settings(IN_UNIT_TESTING=True)+class TestAccountAudience(ClickhouseTestMixin, NonAtomicBaseTest):+ def _list(self, filters: AccountAudienceFilters | None = None, cursor: str | None = None, limit: int = 100):+ return list_account_external_ids_for_audience(+ self.team, filters or AccountAudienceFilters(), cursor=cursor, limit=limit+ )++ def _custom_property_filters(self, definition_id, operator: str, value=None) -> AccountAudienceFilters:+ return AccountAudienceFilters(+ custom_properties=(+ AccountAudienceCustomPropertyFilter(definition_id=definition_id, operator=operator, value=value),+ )+ )++ def test_pages_external_ids_in_order_and_skips_accounts_without_one(self):+ create_account(team_id=self.team.id, name="C", external_id="c1")+ create_account(team_id=self.team.id, name="A", external_id="a1")+ create_account(team_id=self.team.id, name="B", external_id="b1")+ create_account(team_id=self.team.id, name="No key", external_id=None)++ first_page = self._list(limit=2)+ assert first_page == ["a1", "b1"]+ assert self._list(cursor=first_page[-1], limit=2) == ["c1"]++ def test_scopes_to_team(self):+ create_account(team_id=self.team.id, name="Mine", external_id="mine")+ other_team = Team.objects.create(organization=self.organization)+ create_account(team_id=other_team.id, name="Theirs", external_id="theirs")++ assert self._list() == ["mine"]++ def test_tag_filter_narrows(self):+ tagged = create_account(team_id=self.team.id, name="Tagged", external_id="tagged")+ create_account(team_id=self.team.id, name="Untagged", external_id="untagged")+ set_tags_on_object(["vip"], tagged)++ assert self._list(AccountAudienceFilters(tag_names=("vip",))) == ["tagged"]++ def test_assignment_filters_narrow(self):+ holder = self._create_user("[email protected]")+ assigned = create_account(team_id=self.team.id, name="Assigned", external_id="assigned")+ create_account(team_id=self.team.id, name="Unassigned", external_id="unassigned")+ definition, _ = AccountRelationshipDefinition.objects.for_team(self.team.id).get_or_create(+ team_id=self.team.id, name="CSM"+ )+ relationships_logic.assign(+ team_id=self.team.id, account=assigned, definition=definition, user=holder, created_by=holder+ )++ assert self._list(AccountAudienceFilters(assigned_to_user_ids=(holder.id,))) == ["assigned"]+ assert self._list(AccountAudienceFilters(all_roles_unassigned=True)) == ["unassigned"]++ @parameterized.expand(+ [+ ("exact_string", "text", {"value_str": "Enterprise"}, {"value_str": "Startup"}, "exact", ["Enterprise"]),+ (+ "exact_multi_value",+ "text",+ {"value_str": "Enterprise"},+ {"value_str": "Startup"},+ "exact",+ ["Enterprise", "Mid-market"],+ ),+ ("icontains", "text", {"value_str": "Enterprise plan"}, {"value_str": "Startup"}, "icontains", ["enter"]),+ ("regex", "text", {"value_str": "tier-9"}, {"value_str": "tier-x"}, "regex", ["tier-[0-9]+"]),+ ("numeric_gt", "number", {"value_num": 100}, {"value_num": 5}, "gt", [50]),+ ("boolean_exact", "boolean", {"value_bool": True}, {"value_bool": False}, "exact", ["true"]),+ (+ "date_before",+ "datetime",+ {"value_datetime": datetime(2026, 1, 10, tzinfo=UTC)},+ {"value_datetime": datetime(2026, 6, 10, tzinfo=UTC)},+ "is_date_before",+ ["2026-03-01"],+ ),+ ]+ )+ def test_custom_property_operators_narrow(self, _name, display_type, match_value, other_value, operator, value):+ definition = create_custom_property_definition(team_id=self.team.id, name="Prop", display_type=display_type)+ match = create_account(team_id=self.team.id, name="Match", external_id="match")+ other = create_account(team_id=self.team.id, name="Other", external_id="other")+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=match, definition=definition, **match_value+ )+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=other, definition=definition, **other_value+ )++ assert self._list(self._custom_property_filters(definition.id, operator, value)) == ["match"]++ def test_is_not_keeps_accounts_without_a_value(self):+ definition = create_custom_property_definition(team_id=self.team.id, name="Tier")+ excluded = create_account(team_id=self.team.id, name="Excluded", external_id="excluded")+ create_account(team_id=self.team.id, name="Unset", external_id="unset")+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=excluded, definition=definition, value_str="Enterprise"+ )++ assert self._list(self._custom_property_filters(definition.id, "is_not", ["Enterprise"])) == ["unset"]++ def test_is_set_and_is_not_set(self):+ definition = create_custom_property_definition(team_id=self.team.id, name="Tier")+ with_value = create_account(team_id=self.team.id, name="With", external_id="with")+ create_account(team_id=self.team.id, name="Without", external_id="without")+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=with_value, definition=definition, value_str="x"+ )++ assert self._list(self._custom_property_filters(definition.id, "is_set")) == ["with"]+ assert self._list(self._custom_property_filters(definition.id, "is_not_set")) == ["without"]++ def test_unknown_definition_id_fails_resolution(self):+ # Dropping the predicate would silently broaden the audience to every account.+ create_account(team_id=self.team.id, name="A", external_id="a1")++ with self.assertRaisesRegex(ValueError, "deleted or unknown custom property"):+ self._list(self._custom_property_filters(uuid4(), "exact", ["x"]))++ def test_type_incompatible_value_fails_resolution(self):+ definition = create_custom_property_definition(team_id=self.team.id, name="MRR", display_type="number")+ create_account(team_id=self.team.id, name="A", external_id="a1")++ with self.assertRaisesRegex(ValueError, "incompatible"):+ self._list(self._custom_property_filters(definition.id, "exact", ["not-a-number"]))++ def test_count_matches_list(self):+ tagged = create_account(team_id=self.team.id, name="Tagged", external_id="tagged")+ create_account(team_id=self.team.id, name="Untagged", external_id="untagged")+ create_account(team_id=self.team.id, name="No key", external_id=None)+ set_tags_on_object(["vip"], tagged)++ assert count_accounts_for_audience(self.team, AccountAudienceFilters()) == 2+ filters = AccountAudienceFilters(tag_names=("vip",))+ assert count_accounts_for_audience(self.team, filters) == len(self._list(filters))diff --git a/products/customer_analytics/backend/test/test_account_audience_provider.py b/products/customer_analytics/backend/test/test_account_audience_provider.pynew file mode 100644index 000000000000..0566e013d7f0--- /dev/null+++ b/products/customer_analytics/backend/test/test_account_audience_provider.py@@ -0,0 +1,17 @@+from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest++from django.test import override_settings++from products.customer_analytics.backend.test.factories import create_account+from products.workflows.backend.services.account_audience import get_account_audience_count, get_account_audience_page+++@override_settings(IN_UNIT_TESTING=True)+class TestAccountAudienceProviderWiring(ClickhouseTestMixin, NonAtomicBaseTest):+ def test_workflows_service_resolves_through_the_registered_provider(self):+ create_account(team_id=self.team.id, name="A", external_id="a1")+ create_account(team_id=self.team.id, name="No key", external_id=None)++ filters = {"audience_type": "accounts"}+ assert get_account_audience_page(self.team, filters, cursor=None) == ["a1"]+ assert get_account_audience_count(self.team, filters) == 1diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 9c03203c918a..7f64a908230a 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -64,7 +64,8 @@ from posthog.plugins.plugin_server_api import (rerun_hog_invocations,)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin-from posthog.rbac.user_access_control import UserAccessControlSerializerMixin+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlSerializerMixin+from posthog.synthetic_user import SyntheticUserfrom posthog.utils import relative_date_parse_with_delta_mappingfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate@@ -104,6 +105,14 @@ from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedulefrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfigfrom products.workflows.backend.providers.ses import SESProvider+from products.workflows.backend.services.account_audience import (+ ACCOUNT_BATCH_SIZE,+ get_account_audience_count,+ get_account_audience_page,+ get_account_group_type_name,+ is_account_audience,+ parse_account_audience_filters,+)from products.workflows.backend.services.batch_audience import (PERSON_BATCH_SIZE as WORKFLOWS_PERSON_BATCH_SIZE,SUPPORTED_DEDUPE_KEYS,@@ -775,6 +784,10 @@ class HogFlowActionSerializer(serializers.Serializer):"actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, ""type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} ""to reference a cohort. "+ "batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts "+ "audience fans out one run per customer analytics account and takes account filters instead: "+ "properties entries of type 'account_custom_property' (key = definition id), plus "+ "tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. ""function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable ""hog templating ({person.x}, {event.x}); flat strings won't interpolate. ""function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open "@@ -901,9 +914,15 @@ class HogFlowActionSerializer(serializers.Serializer):if properties is not None and not isinstance(properties, list):raise serializers.ValidationError({"filters": {"properties": "Properties must be an array."}})if strict and isinstance(filters, dict):- # The audience targets who a person is (properties / cohort membership), not what they did.- # Event/action filters are silently dropped by the person-based blast radius (resolving to- # "everyone"), so reject them outright — same rejection as a behavioral cohort below.+ audience_type = filters.get("audience_type")+ if audience_type not in (None, "persons", "accounts"):+ raise serializers.ValidationError(+ {"filters": {"audience_type": "Must be 'persons' or 'accounts'."}}+ )+ # The audience targets who a person/account is (properties / cohort membership), not what+ # they did. Event/action filters are silently dropped by the person-based blast radius+ # (resolving to "everyone"), so reject them outright — same rejection as a behavioral+ # cohort below.if filters.get("events") or filters.get("actions"):raise serializers.ValidationError({@@ -914,7 +933,35 @@ class HogFlowActionSerializer(serializers.Serializer):)})- self._reject_behavioral_cohorts_in_audience(filters.get("properties"))+ if audience_type == "accounts":+ team = self.context["get_team"]()+ if get_account_group_type_name(team) is None:+ raise serializers.ValidationError(+ {+ "filters": (+ "Configure a customer analytics account group type before using "+ "an account audience."+ )+ }+ )+ # Resolution runs under a service principal, so account access is+ # enforced here, when a person configures the audience.+ request = self.context.get("request")+ user = getattr(request, "user", None)+ if (+ user is not None+ and user.is_authenticated+ and not isinstance(user, SyntheticUser)+ and not UserAccessControl(user=user, team=team).check_access_level_for_resource(+ "account", "viewer"+ )+ ):+ raise serializers.ValidationError(+ {"filters": "You do not have access to customer analytics accounts."}+ )+ parse_account_audience_filters(filters)+ else:+ self._reject_behavioral_cohorts_in_audience(filters.get("properties"))elif data.get("config", {}).get("type") == "schedule":# The schedule definition lives on a separate HogFlowSchedule row, but a schedule trigger# resolves the same offline audience as batch — guard its cohort refs the same way.@@ -3448,6 +3495,24 @@ class HogFlowViewSet(group_type_index = params.get("group_type_index")dedupe_key = params.get("dedupe_key")+ if is_account_audience(filters):+ # Account audiences never touch person data or flag conditions; the parse inside+ # the count rejects anything but account filters. Sizing the audience reads account+ # data, so it requires the same access the audience editor requires.+ if not self.user_access_control.check_access_level_for_resource("account", "viewer"):+ raise exceptions.PermissionDenied("You do not have access to customer analytics accounts.")+ return Response(+ BlastRadiusSerializer(+ {+ "affected": get_account_audience_count(self.team, filters),+ "total": get_account_audience_count(self.team, {"audience_type": "accounts"}),+ "limit": get_hogflow_batch_trigger_limit(self.team_id),+ "dedupe_key": None,+ "confirm_token": mint_audience_confirm_token(self.team_id, filters, None, None),+ }+ ).data+ )+reject_flag_conditions_in_audience(self.team, filters)# Preview matches the actual send: with dedup active, "affected" is the number of@@ -4097,6 +4162,43 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMilogger.exception("Error in internal_user_blast_radius_persons", error=str(e), team_id=team_id)return Response({"error": "Internal server error"}, status=500)+ def internal_account_audience(self, request: Request, team_id: str) -> Response:+ """+ Internal endpoint for the Node batch resolver to page an account audience.+ Requires Bearer token authentication via INTERNAL_API_SECRET.+ """+ if request.method != "POST":+ return Response({"error": "Method not allowed"}, status=405)++ try:+ team = Team.objects.get(id=int(team_id))+ except (Team.DoesNotExist, ValueError):+ return Response({"error": "Team not found"}, status=404)++ filters = request.data.get("filters") or {}+ if not is_account_audience(filters):+ return Response({"error": "Filters must declare audience_type 'accounts'"}, status=400)+ group_type = get_account_group_type_name(team)+ if group_type is None:+ return Response({"error": "No customer analytics account group type configured"}, status=400)++ cursor = request.data.get("cursor")+ try:+ accounts = get_account_audience_page(team, filters, cursor)+ return Response(+ {+ "accounts": accounts,+ "cursor": accounts[-1] if accounts else None,+ "has_more": len(accounts) == ACCOUNT_BATCH_SIZE,+ "group_type": group_type,+ }+ )+ except exceptions.ValidationError as e:+ return Response({"error": _validation_error_message(e)}, status=400)+ except Exception as e:+ logger.exception("Error in internal_account_audience", error=str(e), team_id=team_id)+ return Response({"error": "Internal server error"}, status=500)+def internal_process_due_schedules(self, request: Request, **kwargs) -> Response:"""Internal endpoint called by the scheduler service to process due schedules.diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 76aab6e8d080..b7cb4f51c9e1 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -14,8 +14,9 @@ from rest_framework import statusfrom posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.cdp.templates.slack.template_slack import template as template_slack+from posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSource-from posthog.models import Organization, Team, User+from posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -32,8 +33,25 @@ from products.workflows.backend.api.hog_flow import (from products.workflows.backend.models.hog_flow.hog_flow import SUPPORTED_ACTION_TYPES, HogFlowfrom products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob+from ee.models.rbac.access_control import AccessControl+webhook_template = MOCK_NODE_TEMPLATES[0]++class _StubAccountAudienceProvider:+ def __init__(self, group_type: str | None):+ self.group_type = group_type++ def count_accounts(self, team, filters) -> int:+ return 0++ def list_account_external_ids(self, team, filters, *, cursor, limit) -> list[str]:+ return []++ def get_account_group_type_name(self, team) -> str | None:+ return self.group_type++_REVISIONS_FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"_SECRET_TEMPLATE_ID = "template-secret-webhook"@@ -2117,6 +2135,169 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)assert response.status_code == 201, response.json()+ def _post_batch_flow(self, filters: dict, status: str = "active"):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {"type": "batch", "filters": filters},+ }+ hog_flow = {"name": "Test Batch Flow", "status": status, "actions": [trigger_action]}+ return self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)++ def _account_audience_provider(self, group_type: str | None = "account"):+ return patch(+ "products.workflows.backend.services.account_audience._provider",+ _StubAccountAudienceProvider(group_type),+ )++ def test_hog_flow_batch_trigger_accounts_audience_saves(self):+ with self._account_audience_provider():+ response = self._post_batch_flow(+ {+ "audience_type": "accounts",+ "properties": [+ {+ "key": "7b0d4a12-8f0e-4c39-9a5f-52dd8f2f7a11",+ "type": "account_custom_property",+ "operator": "exact",+ "value": ["Enterprise"],+ }+ ],+ "tag_names": ["vip"],+ }+ )+ assert response.status_code == 201, response.json()++ @parameterized.expand(+ [+ ("person_property", [{"key": "email", "type": "person", "operator": "icontains", "value": "@x.com"}]),+ ("cohort", [{"key": "id", "type": "cohort", "value": 1, "operator": "in"}]),+ ]+ )+ def test_hog_flow_batch_trigger_accounts_audience_rejects_non_account_filters(self, _name, properties):+ with self._account_audience_provider():+ response = self._post_batch_flow({"audience_type": "accounts", "properties": properties})+ assert response.status_code == 400, response.json()+ assert "account custom property" in response.json()["detail"]++ def test_hog_flow_batch_trigger_accounts_audience_rejects_event_filters(self):+ with self._account_audience_provider():+ response = self._post_batch_flow(+ {"audience_type": "accounts", "properties": [], "events": [{"id": "$pageview", "type": "events"}]}+ )+ assert response.status_code == 400, response.json()+ assert "event" in response.json()["detail"].lower()++ def test_hog_flow_batch_trigger_accounts_audience_requires_configured_group_type(self):+ with self._account_audience_provider(group_type=None):+ response = self._post_batch_flow({"audience_type": "accounts", "properties": []})+ assert response.status_code == 400, response.json()+ assert "account group type" in response.json()["detail"]++ def test_hog_flow_batch_trigger_accounts_audience_requires_account_access(self):+ # Resolution runs under a service principal, so authoring is where account access is enforced.+ self.organization.available_product_features = [+ {"key": AvailableFeature.ADVANCED_PERMISSIONS, "name": AvailableFeature.ADVANCED_PERMISSIONS},+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ # Resource-level checks on "account" resolve through its parent resource.+ AccessControl.objects.create(team=self.team, resource="customer_analytics", access_level="none")++ with self._account_audience_provider():+ response = self._post_batch_flow({"audience_type": "accounts", "properties": []})+ assert response.status_code == 400, response.json()+ assert "access" in response.json()["detail"]++ def test_hog_flow_batch_trigger_rejects_unknown_audience_type(self):+ response = self._post_batch_flow({"audience_type": "bogus", "properties": []})+ assert response.status_code == 400, response.json()+ assert "audience_type" in json.dumps(response.json())++ @override_settings(INTERNAL_API_SECRET="test-secret-123")+ def test_internal_account_audience_pages_accounts(self):+ with (+ self._account_audience_provider(),+ patch(+ "products.workflows.backend.api.hog_flow.get_account_audience_page", return_value=["a1", "a2"]+ ) as mock_page,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/account_audience",+ {"filters": {"audience_type": "accounts", "properties": []}, "cursor": "a0"},+ format="json",+ headers={"x-internal-api-secret": "test-secret-123"},+ )++ assert response.status_code == 200, response.json()+ assert response.json() == {+ "accounts": ["a1", "a2"],+ "cursor": "a2",+ "has_more": False,+ "group_type": "account",+ }+ mock_page.assert_called_once()++ def test_internal_account_audience_requires_internal_secret(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/account_audience",+ {"filters": {"audience_type": "accounts"}},+ format="json",+ )+ assert response.status_code in (401, 403), response.content++ @parameterized.expand(+ [+ ("persons_filters", {"filters": {"properties": []}}),+ ("missing_filters", {}),+ ]+ )+ @override_settings(INTERNAL_API_SECRET="test-secret-123")+ def test_internal_account_audience_rejects_non_account_filters(self, _name, body):+ with self._account_audience_provider():+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/account_audience",+ body,+ format="json",+ headers={"x-internal-api-secret": "test-secret-123"},+ )+ assert response.status_code == 400, response.json()++ @override_settings(INTERNAL_API_SECRET="test-secret-123")+ def test_internal_account_audience_requires_configured_group_type(self):+ with self._account_audience_provider(group_type=None):+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/account_audience",+ {"filters": {"audience_type": "accounts", "properties": []}},+ format="json",+ headers={"x-internal-api-secret": "test-secret-123"},+ )+ assert response.status_code == 400, response.json()++ def test_user_blast_radius_accounts_audience_counts_accounts(self):+ with (+ self._account_audience_provider(),+ patch(+ "products.workflows.backend.api.hog_flow.get_account_audience_count", side_effect=[3, 10]+ ) as mock_count,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"audience_type": "accounts", "properties": []}},+ format="json",+ )++ assert response.status_code == 200, response.json()+ data = response.json()+ assert data["affected"] == 3+ assert data["total"] == 10+ assert data["dedupe_key"] is None+ assert data["confirm_token"]+ assert mock_count.call_count == 2+def _make_cohort(self, *, behavioral=False, static=False, nested_cohort_id=None) -> Cohort:if behavioral:properties = {diff --git a/products/workflows/backend/services/account_audience.py b/products/workflows/backend/services/account_audience.pynew file mode 100644index 000000000000..46294f66fa35--- /dev/null+++ b/products/workflows/backend/services/account_audience.py@@ -0,0 +1,166 @@+"""Account-scoped batch audiences: one invocation per customer analytics account.++The trigger's stored ``filters`` dict is the single source of truth. ``audience_type:+'accounts'`` switches the batch resolver from persons to accounts; the remaining keys+(``properties`` of account custom property filters, ``tag_names``, ``assigned_to_user_ids``,+``all_roles_unassigned``) narrow which accounts a firing fans out to.++customer_analytics owns the account data but already depends on workflows, so the query+implementation arrives through a provider registered during ``django.setup()``+(``CustomerAnalyticsConfig.ready``) — the same hook inversion warehouse_sources uses.+"""++from dataclasses import dataclass+from typing import Any, Protocol+from uuid import UUID++from rest_framework import exceptions++from posthog.models.team.team import Team++ACCOUNT_BATCH_SIZE = 500++# Mirrors ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST in+# products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts.+SUPPORTED_CUSTOM_PROPERTY_OPERATORS = frozenset(+ {+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after",+ }+)++_VALUELESS_OPERATORS = frozenset({"is_set", "is_not_set"})+++@dataclass(frozen=True, kw_only=True)+class AccountAudienceCustomPropertyFilter:+ """One custom-property predicate of a batch audience (key = definition id)."""++ definition_id: UUID+ operator: str+ value: Any = None+++@dataclass(frozen=True, kw_only=True)+class AccountAudienceFilters:+ """Account selection for a batch run; empty filters mean every account with an external_id."""++ tag_names: tuple[str, ...] = ()+ assigned_to_user_ids: tuple[int, ...] = ()+ all_roles_unassigned: bool = False+ custom_properties: tuple[AccountAudienceCustomPropertyFilter, ...] = ()+++class AccountAudienceProvider(Protocol):+ def count_accounts(self, team: Team, filters: AccountAudienceFilters) -> int: ...++ def list_account_external_ids(+ self, team: Team, filters: AccountAudienceFilters, *, cursor: str | None, limit: int+ ) -> list[str]: ...++ def get_account_group_type_name(self, team: Team) -> str | None: ...+++_provider: AccountAudienceProvider | None = None+++def register_account_audience_provider(provider: AccountAudienceProvider) -> None:+ global _provider+ _provider = provider+++def _require_provider() -> AccountAudienceProvider:+ if _provider is None:+ raise exceptions.ValidationError({"filters": "Account audiences are not available on this instance."})+ return _provider+++def is_account_audience(filters: dict | None) -> bool:+ return bool(filters) and filters.get("audience_type") == "accounts" # type: ignore[union-attr]+++def get_account_group_type_name(team: Team) -> str | None:+ return _provider.get_account_group_type_name(team) if _provider is not None else None+++def parse_account_audience_filters(filters: dict) -> AccountAudienceFilters:+ properties = filters.get("properties") or []+ if not isinstance(properties, list):+ raise exceptions.ValidationError({"filters": {"properties": "Properties must be an array."}})++ custom_properties: list[AccountAudienceCustomPropertyFilter] = []+ for entry in properties:+ if not isinstance(entry, dict) or entry.get("type") != "account_custom_property":+ raise exceptions.ValidationError(+ {"filters": {"properties": "Account audiences only support account custom property filters."}}+ )+ try:+ definition_id = UUID(str(entry.get("key")))+ except (ValueError, TypeError):+ raise exceptions.ValidationError(+ {"filters": {"properties": "Account custom property filter keys must be property definition ids."}}+ )+ operator = str(entry.get("operator") or "exact")+ # A dropped predicate would silently broaden a mass send to every account, so anything+ # the compiler can't express is rejected at write time instead.+ if operator not in SUPPORTED_CUSTOM_PROPERTY_OPERATORS:+ raise exceptions.ValidationError(+ {"filters": {"properties": f"Unsupported operator for account audiences: {operator}"}}+ )+ value = entry.get("value")+ if operator not in _VALUELESS_OPERATORS and value in (None, "", []):+ raise exceptions.ValidationError(+ {"filters": {"properties": f"A value is required for the {operator} operator."}}+ )+ custom_properties.append(+ AccountAudienceCustomPropertyFilter(+ definition_id=definition_id,+ operator=operator,+ value=value,+ )+ )++ tag_names = filters.get("tag_names") or []+ if not isinstance(tag_names, list) or not all(isinstance(tag, str) for tag in tag_names):+ raise exceptions.ValidationError({"filters": {"tag_names": "Must be a list of tag names."}})++ assigned_to_user_ids = filters.get("assigned_to_user_ids") or []+ if not isinstance(assigned_to_user_ids, list) or not all(+ isinstance(user_id, int) and not isinstance(user_id, bool) for user_id in assigned_to_user_ids+ ):+ raise exceptions.ValidationError({"filters": {"assigned_to_user_ids": "Must be a list of user ids."}})++ return AccountAudienceFilters(+ tag_names=tuple(tag_names),+ assigned_to_user_ids=tuple(assigned_to_user_ids),+ all_roles_unassigned=bool(filters.get("all_roles_unassigned")),+ custom_properties=tuple(custom_properties),+ )+++def get_account_audience_page(team: Team, filters: dict, cursor: str | None) -> list[str]:+ parsed = parse_account_audience_filters(filters)+ try:+ return _require_provider().list_account_external_ids(team, parsed, cursor=cursor, limit=ACCOUNT_BATCH_SIZE)+ except ValueError as e:+ raise exceptions.ValidationError({"filters": str(e)})+++def get_account_audience_count(team: Team, filters: dict) -> int:+ try:+ return _require_provider().count_accounts(team, parse_account_audience_filters(filters))+ except ValueError as e:+ raise exceptions.ValidationError({"filters": str(e)})diff --git a/products/workflows/backend/test/test_account_audience_filters.py b/products/workflows/backend/test/test_account_audience_filters.pynew file mode 100644index 000000000000..7c12079caaa8--- /dev/null+++ b/products/workflows/backend/test/test_account_audience_filters.py@@ -0,0 +1,83 @@+from uuid import uuid4++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import exceptions++from products.workflows.backend.services.account_audience import is_account_audience, parse_account_audience_filters+++class TestParseAccountAudienceFilters(SimpleTestCase):+ def test_valid_filters_round_trip(self):+ definition_id = uuid4()+ parsed = parse_account_audience_filters(+ {+ "audience_type": "accounts",+ "properties": [+ {"key": str(definition_id), "type": "account_custom_property", "operator": "exact", "value": ["x"]}+ ],+ "tag_names": ["vip"],+ "assigned_to_user_ids": [7],+ "all_roles_unassigned": True,+ }+ )++ assert parsed.tag_names == ("vip",)+ assert parsed.assigned_to_user_ids == (7,)+ assert parsed.all_roles_unassigned is True+ assert parsed.custom_properties[0].definition_id == definition_id+ assert parsed.custom_properties[0].operator == "exact"+ assert parsed.custom_properties[0].value == ["x"]++ @parameterized.expand(+ [+ ("person_property_entry", {"properties": [{"key": "email", "type": "person", "operator": "exact"}]}),+ ("cohort_entry", {"properties": [{"key": "id", "type": "cohort", "value": 1, "operator": "in"}]}),+ ("non_uuid_key", {"properties": [{"key": "tier", "type": "account_custom_property", "operator": "exact"}]}),+ ("non_list_properties", {"properties": "nope"}),+ (+ "unknown_operator",+ {+ "properties": [+ {+ "key": "7b0d4a12-8f0e-4c39-9a5f-52dd8f2f7a11",+ "type": "account_custom_property",+ "operator": "equals",+ "value": ["x"],+ }+ ]+ },+ ),+ (+ "missing_value",+ {+ "properties": [+ {+ "key": "7b0d4a12-8f0e-4c39-9a5f-52dd8f2f7a11",+ "type": "account_custom_property",+ "operator": "exact",+ "value": [],+ }+ ]+ },+ ),+ ("non_list_tag_names", {"tag_names": "vip"}),+ ("non_str_tag_entries", {"tag_names": [1]}),+ ("non_int_user_ids", {"assigned_to_user_ids": ["7"]}),+ ]+ )+ def test_malformed_filters_raise(self, _name, overrides):+ with self.assertRaises(exceptions.ValidationError):+ parse_account_audience_filters({"audience_type": "accounts", **overrides})++ @parameterized.expand(+ [+ ("accounts", {"audience_type": "accounts"}, True),+ ("persons_explicit", {"audience_type": "persons"}, False),+ ("absent", {}, False),+ ("none", None, False),+ ]+ )+ def test_is_account_audience(self, _name, filters, expected):+ assert is_account_audience(filters) is expecteddiff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsxindex 7737b7282e45..9f535375f078 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx@@ -24,11 +24,15 @@ const TriggerPopover = ({const { workflow, variableValues, inputs } = useValues(logic)const { setInput, clearInputs, triggerManualWorkflow, triggerBatchWorkflow } = useActions(logic)+ const isAccountAudience =+ workflow?.trigger?.type === 'batch' && workflow.trigger.filters?.audience_type === 'accounts'+const { blastRadius, blastRadiusLoading } = useValues(batchTriggerLogic({id: props.id,filters: workflow?.trigger?.type === 'batch' ? workflow?.trigger?.filters : undefined,- dedupeKey: getAudienceDedupeKey(workflow),+ // Account audiences carry no person, so email dedup never applies to them.+ dedupeKey: isAccountAudience ? undefined : getAudienceDedupeKey(workflow),}))@@ -40,7 +44,8 @@ const TriggerPopover = ({const blastRadiusSuffix = (): string => {if (workflow?.trigger?.type === 'batch') {- return blastRadius ? ` for ${humanFriendlyNumber(blastRadius.affected)} users` : ' for ...'+ const noun = isAccountAudience ? 'accounts' : 'users'+ return blastRadius ? ` for ${humanFriendlyNumber(blastRadius.affected)} ${noun}` : ' for ...'}return ''}@@ -109,7 +114,7 @@ const TriggerPopover = ({loading={blastRadiusLoading}disabledReason={blastRadiusExceeded && blastRadius?.limit != null- ? `Batch size exceeds the limit of ${humanFriendlyNumber(blastRadius.limit)} users. Add filters to narrow your audience. This limit will be loosened in the future.`+ ? `Batch size exceeds the limit of ${humanFriendlyNumber(blastRadius.limit)} ${isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow your audience. This limit will be loosened in the future.`: undefined}onClick={() => {diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButtonLogic.ts b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButtonLogic.tsindex d3b6021a58f5..29cdf94837b7 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButtonLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButtonLogic.ts@@ -45,11 +45,19 @@ export interface hogFlowManualTriggerButtonLogicActions {triggerBatchWorkflow: (variables: Record<string, any>,filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}) => {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}variables: Record<string, any>} // workflowLogicdiff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 38af2a6fab7a..66e137a103c3 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -714,12 +714,6 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -729,6 +723,16 @@ export interface hogFlowEditorLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {filters: {properties?: any[] | undefined@@ -852,12 +856,6 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -867,6 +865,16 @@ export interface hogFlowEditorLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {filters: {properties?: any[] | undefined@@ -1500,12 +1508,6 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -1515,6 +1517,16 @@ export interface hogFlowEditorLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {filters: {properties?: any[] | undefined@@ -1638,12 +1650,6 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -1653,6 +1659,16 @@ export interface hogFlowEditorLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {filters: {properties?: any[] | undefineddiff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.tsindex 5cf309e567f4..e80981f1ec09 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts@@ -358,7 +358,11 @@ export interface hogFlowEditorTestLogicMeta {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -470,7 +474,11 @@ export interface hogFlowEditorTestLogicMeta {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 59662c678fda..b38e273c5246 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -14,20 +14,26 @@ import {IconWebhooks,} from '@posthog/icons'import {+ LemonBanner,LemonButton,+ LemonCheckbox,LemonCollapse,LemonDivider,LemonDropdown,LemonInput,+ LemonInputSelect,LemonLabel,+ LemonSegmentedButton,LemonSelect,Spinner,Tooltip,} from '@posthog/lemon-ui'import { CodeSnippet } from 'lib/components/CodeSnippet'+import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { FEATURE_FLAGS } from 'lib/constants'import { IconAdsClick } from 'lib/lemon-ui/icons'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'@@ -37,9 +43,13 @@ import { createFuse } from 'lib/utils/fuseSearch'import { humanFriendlyNumber } from 'lib/utils/numbers'import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter/TestAccountFilter'+import { teamLogic } from 'scenes/teamLogic'+import { tagsModel } from '~/models/tagsModel'import { PropertyFilterType } from '~/types'+import { accountsColumnConfigLogic } from 'products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic'+import { ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST } from 'products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters'// Side-effect imports: register product-specific trigger typesimport 'products/workflows/frontend/Workflows/hogflows/registry/triggers'@@ -506,7 +516,9 @@ function StepTriggerConfigurationManual(): JSX.Element {function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filters: any }): JSX.Element | null {const { workflow } = useValues(workflowLogic)- const dedupeKey = getAudienceDedupeKey(workflow)+ const isAccountAudience = filters?.audience_type === 'accounts'+ // Account audiences carry no person, so email dedup never applies to them.+ const dedupeKey = isAccountAudience ? undefined : getAudienceDedupeKey(workflow)const logic = batchTriggerLogic({ id: actionId, filters, dedupeKey })const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(logic)@@ -543,12 +555,14 @@ function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filreturn (<div className="text-muted"><div className={exceeded ? 'text-danger font-semibold' : 'text-muted'}>- approximately {humanFriendlyNumber(affected)} of {humanFriendlyNumber(total)} persons.+ approximately {humanFriendlyNumber(affected)} of {humanFriendlyNumber(total)}{' '}+ {isAccountAudience ? 'accounts' : 'persons'}.</div>{exceeded && limit != null && (<div className="text-danger text-xs">- Batch size exceeds the limit of {humanFriendlyNumber(limit)} users. Add filters to narrow your- audience. This limit will be loosened in the future.+ Batch size exceeds the limit of {humanFriendlyNumber(limit)}{' '}+ {isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow your audience. This limit will+ be loosened in the future.</div>)}</div>@@ -568,6 +582,90 @@ function BatchScheduleSection(): JSX.Element {)}+type BatchTriggerFilters = Extract<HogFlowAction['config'], { type: 'batch' }>['filters']++function StepTriggerBatchAccountFilters({+ actionId,+ filters,+}: {+ actionId: string+ filters: BatchTriggerFilters+}): JSX.Element {+ const { partialSetWorkflowActionConfig } = useActions(workflowLogic)+ const { tags: tagsAvailable } = useValues(tagsModel)+ const { customPropertyTaxonomicOptions } = useValues(accountsColumnConfigLogic)++ const setFilters = (update: Partial<BatchTriggerFilters>): void => {+ partialSetWorkflowActionConfig(actionId, { filters: { ...filters, ...update } })+ }++ const assignedToUserIds = filters.assigned_to_user_ids ?? []++ return (+ <div className="flex flex-col gap-2">+ <LemonBanner type="info" className="w-full">+ Account audiences run one workflow per account, without a person. Steps that read person properties+ won't fill in. Use the "Get account" step to read account data.+ </LemonBanner>+ <div className="flex flex-wrap gap-2 items-center">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ size="small"+ className="min-w-48"+ value={filters.tag_names ?? []}+ options={(tagsAvailable || []).map((tag: string) => ({ key: tag, label: tag }))}+ onChange={(tag_names) => setFilters({ tag_names })}+ placeholder="Filter by tags"+ data-attr="workflows-batch-account-tags-filter"+ />+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="p-2 min-w-64 flex flex-col gap-2">+ <LemonCheckbox+ checked={!!filters.all_roles_unassigned}+ onChange={(all_roles_unassigned) => setFilters({ all_roles_unassigned })}+ label="Unassigned only"+ data-attr="workflows-batch-account-unassigned-filter"+ />+ <LemonDivider className="my-0" />+ <MemberSelectMultiple+ idKey="id"+ value={assignedToUserIds}+ onChange={(users) => setFilters({ assigned_to_user_ids: users.map((user) => user.id) })}+ />+ </div>+ }+ >+ <LemonButton type="secondary" size="small" data-attr="workflows-batch-account-assigned-filter">+ {filters.all_roles_unassigned+ ? 'Unassigned'+ : assignedToUserIds.length === 0+ ? 'Assigned to anyone'+ : `Assigned to ${assignedToUserIds.length} ${assignedToUserIds.length === 1 ? 'person' : 'people'}`}+ </LemonButton>+ </LemonDropdown>+ </div>+ {customPropertyTaxonomicOptions.length > 0 && (+ <PropertyFilters+ pageKey={`workflows-batch-trigger-account-filters-${actionId}`}+ propertyFilters={filters.properties}+ addText="Add condition"+ sendAllKeyUpdates+ onChange={(properties) => setFilters({ properties })}+ taxonomicGroupTypes={[TaxonomicFilterGroupType.AccountCustomProperties]}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.AccountCustomProperties]: customPropertyTaxonomicOptions,+ }}+ hasRowOperator={false}+ operatorAllowlist={ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST}+ />+ )}+ </div>+ )+}+function StepTriggerConfigurationBatch({action,config,@@ -576,45 +674,73 @@ function StepTriggerConfigurationBatch({config: Extract<HogFlowAction['config'], { type: 'batch' }>}): JSX.Element {const { partialSetWorkflowActionConfig } = useActions(workflowLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const { currentTeam } = useValues(teamLogic)++ const accountAudienceAvailable =+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] &&+ currentTeam?.customer_analytics_config?.account_group_type_index != null+ const isAccountAudience = config.filters.audience_type === 'accounts'return (<div className="flex flex-col gap-2 my-2 w-full">- <div>- <span className="font-semibold">This batch will include</span>{' '}- <StepTriggerAffectedUsers actionId={action.id} filters={config.filters} />- </div>- <div>- <PropertyFilters- pageKey={`workflows-batch-trigger-property-filters-${action.id}`}- propertyFilters={config.filters.properties}- addText="Add condition"- orFiltering- sendAllKeyUpdates- allowRelativeDateOptions- {...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}- hideBehavioralCohorts- logicalRowDivider- onChange={(properties) =>+ {(accountAudienceAvailable || isAccountAudience) && (+ <LemonSegmentedButton+ size="small"+ value={isAccountAudience ? 'accounts' : 'persons'}+ onChange={(audience_type) =>+ // Person and account filters are mutually invalid, so switching resets them.partialSetWorkflowActionConfig(action.id, {- filters: {- properties,- },+ filters: { audience_type, properties: [] },})}- taxonomicGroupTypes={[- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.Cohorts,- TaxonomicFilterGroupType.Metadata,+ options={[+ { value: 'persons' as const, label: 'People' },+ { value: 'accounts' as const, label: 'Accounts' },]}- taxonomicFilterOptionsFromProp={{- [TaxonomicFilterGroupType.Metadata]: [- { name: 'distinct_id', propertyFilterType: PropertyFilterType.Person },- ],- }}- hasRowOperator={false}- operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}+ data-attr="workflows-batch-audience-type"/>+ )}+ <div>+ <span className="font-semibold">This batch will include</span>{' '}+ <StepTriggerAffectedUsers actionId={action.id} filters={config.filters} /></div>+ {isAccountAudience ? (+ <StepTriggerBatchAccountFilters actionId={action.id} filters={config.filters} />+ ) : (+ <div>+ <PropertyFilters+ pageKey={`workflows-batch-trigger-property-filters-${action.id}`}+ propertyFilters={config.filters.properties}+ addText="Add condition"+ orFiltering+ sendAllKeyUpdates+ allowRelativeDateOptions+ {...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}+ hideBehavioralCohorts+ logicalRowDivider+ onChange={(properties) =>+ partialSetWorkflowActionConfig(action.id, {+ filters: {+ properties,+ },+ })+ }+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.Cohorts,+ TaxonomicFilterGroupType.Metadata,+ ]}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.Metadata]: [+ { name: 'distinct_id', propertyFilterType: PropertyFilterType.Person },+ ],+ }}+ hasRowOperator={false}+ operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}+ />+ </div>+ )}<BatchScheduleSection /></div>diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.tsindex 12bf0ca8e50e..2cdf1ff8fda4 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts@@ -77,7 +77,11 @@ export interface stepDelayLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -334,12 +338,6 @@ export interface stepDelayLogicActions {}[]delay_duration?: string | undefined}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -349,6 +347,16 @@ export interface stepDelayLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {condition: {filters?:diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.tsindex 21b5bc995942..e6bc4aa84d31 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts@@ -125,7 +125,11 @@ export interface stepWaitUntilTimeWindowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -383,12 +387,6 @@ export interface stepWaitUntilTimeWindowLogicActions {}[]delay_duration?: string | undefined}- | {- filters: {- properties: any[]- }- type: 'batch'- }| {filters: {actions?: any[] | undefined@@ -398,6 +396,16 @@ export interface stepWaitUntilTimeWindowLogicActions {}type: 'event'}+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }| {condition: {filters?:diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 09c8e5f47f7d..6b2038567900 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -160,7 +160,12 @@ export const HogFlowTriggerSchema = z.discriminatedUnion('type', [z.object({type: z.literal('batch'),filters: z.object({+ // 'accounts' fans out one run per customer analytics account instead of per person+ audience_type: z.enum(['persons', 'accounts']).optional(),properties: z.array(z.any()),+ tag_names: z.array(z.string()).optional(),+ assigned_to_user_ids: z.array(z.number()).optional(),+ all_roles_unassigned: z.boolean().optional(),}),}),z.object({diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 69c95e116789..339cadd8d799 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -659,7 +659,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -907,7 +911,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -1445,7 +1453,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -1693,7 +1705,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -1853,7 +1869,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -2183,7 +2203,11 @@ export interface workflowLogicActions {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -2469,7 +2493,11 @@ export interface workflowLogicActions {>['filters']) => {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}variables: Record<string, any>}@@ -2532,7 +2560,11 @@ export interface workflowLogicMeta {}| {filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ audience_type?: 'accounts' | 'persons' | undefinedproperties: any[]+ tag_names?: string[] | undefined}type: 'batch'}@@ -3158,7 +3190,12 @@ export const workflowLogic = kea<workflowLogicType>([}}} else if (action.config.type === 'batch') {- if (!action.config.filters.properties?.length) {+ // Accounts audiences may legitimately target every account — the+ // blast-radius preview and confirm token guard the send instead.+ if (+ action.config.filters.audience_type !== 'accounts' &&+ !action.config.filters.properties?.length+ ) {result.valid = falseresult.errors = {filters: 'At least one property filter is required for batch workflows',diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex c3a48135fdf2..8a1b6d19a6b1 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -415,7 +415,7 @@ export const HogFlowActionTypeEnumApi = {} as const/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.+ * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.*/export type HogFlowActionApiConfig =| { [key: string]: unknown }@@ -476,7 +476,7 @@ export interface HogFlowActionApi {* * `random_cohort_branch` - random_cohort_branch* * `exit` - exit */type: HogFlowActionTypeEnumApi- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */+ /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */config: HogFlowActionApiConfig/** Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those. */output_variable?: unknowndiff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex ce70605dd815..6a36f6a3312b 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -931,6 +931,21 @@ export const hogFlowsUserBlastRadiusCreate = async (})}+export const getInternalHogFlowsAccountAudienceCreateUrl = (teamId: string) => {+ return `/api/projects/${teamId}/internal/hog_flows/account_audience`+}++/**+ * Internal endpoint for the Node batch resolver to page an account audience.+ * Requires Bearer token authentication via INTERNAL_API_SECRET.+ */+export const internalHogFlowsAccountAudienceCreate = async (teamId: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getInternalHogFlowsAccountAudienceCreateUrl(teamId), {+ ...options,+ method: 'POST',+ })+}+export const getInternalHogFlowsBatchJobsStatusUpdateUrl = (teamId: string, batchJobId: string) => {return `/api/projects/${teamId}/internal/hog_flows/batch_jobs/${batchJobId}/status`}diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex e212a23b5386..4d4f5a8af8c4 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -704,7 +704,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -1048,7 +1048,7 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -1397,7 +1397,7 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -2001,7 +2001,7 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -2571,7 +2571,7 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex f99d0501df69..03b05fb84b77 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -102,6 +102,9 @@ tools:hog-flows-user-blast-radius-create:operation: hog_flows_user_blast_radius_createenabled: false+ internal-hog-flows-account-audience-create:+ operation: internal_hog_flows_account_audience_create+ enabled: falseinternal-hog-flows-batch-jobs-status-update:operation: internal_hog_flows_batch_jobs_status_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 633d6020acc6..fee352afa8e4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34995,7 +34995,7 @@ export namespace Schemas {} as const;/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.+ * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.*/export type HogFlowActionConfig = { [key: string]: unknown } | {/** Property-based wait condition; continues when the person matches. A condition with no property filters is ignored — the wait then relies on 'events' and the max_wait_duration timeout. */@@ -35054,7 +35054,7 @@ export namespace Schemas {* * `random_cohort_branch` - random_cohort_branch* * `exit` - exit */type: HogFlowActionTypeEnum;- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */+ /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */config: HogFlowActionConfig;/** Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those. */output_variable?: unknown;diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 9eafc051330c..77a08f6d9dc6 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -360,7 +360,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex 3e04f7505c40..86164d5297ba 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json@@ -193,7 +193,7 @@"type": "object"}],- "description": "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "description": "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."},"created_at": {"description": "Created at (epoch ms). Frontend-managed.",