: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): exit cohort-triggered runs when the person stops matching the cohort (#120429)
Harley Alexanderae11e340ac27
diff --git a/nodejs/src/cdp/_tests/fixtures.ts b/nodejs/src/cdp/_tests/fixtures.tsindex 44562410d1f6..a26d4a024175 100644--- a/nodejs/src/cdp/_tests/fixtures.ts+++ b/nodejs/src/cdp/_tests/fixtures.ts@@ -322,6 +322,7 @@ export interface CohortMembershipRecord {person_id: stringin_cohort: booleanlast_updated?: Date+ version?: string}export const insertCohortMembership = async (diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.tsindex 7716512c79f9..9c3700e7a958 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts@@ -12,11 +12,9 @@ import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { HOG_FLOW_MASK_EXAMPLES } from '../_tests/examples'import { createCohortMembershipEvent, createKafkaMessage } from '../_tests/fixtures'import { insertHogFlow } from '../_tests/fixtures-hogflows'+import { COHORT_MEMBERSHIP_CHANGED_EVENT } from '../services/cohorts/cohort-membership-repository'import { CyclotronJobInvocationHogFlow } from '../types'-import {- COHORT_MEMBERSHIP_CHANGED_EVENT,- CdpCohortMembershipTriggerConsumer,-} from './cdp-cohort-membership-trigger.consumer'+import { CdpCohortMembershipTriggerConsumer } from './cdp-cohort-membership-trigger.consumer'describe('CdpCohortMembershipTriggerConsumer', () => {let processor: CdpCohortMembershipTriggerConsumer@@ -52,7 +50,12 @@ describe('CdpCohortMembershipTriggerConsumer', () => {const matching = await insertHogFlow(hub.postgres, cohortFlow(42, 'entered'))await insertHogFlow(hub.postgres, cohortFlow(42, 'left'))await insertHogFlow(hub.postgres, cohortFlow(7, 'entered'))- const change = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })+ const change = createCohortMembershipEvent({+ team_id: team.id,+ cohort_id: 42,+ status: 'entered',+ last_updated: '2026-10-20 10:00:00.123456',+ })const globals = await processor._parseKafkaBatch([createKafkaMessage(change)])const { invocations, backgroundTask } = await processor.processBatch(globals)@@ -63,6 +66,11 @@ describe('CdpCohortMembershipTriggerConsumer', () => {expect(invocation.functionId).toBe(matching.id)expect(invocation.state.personId).toBe(change.person_id)expect(invocation.state.event.event).toBe(COHORT_MEMBERSHIP_CHANGED_EVENT)+ expect(invocation.state.event.properties).toEqual({+ cohort_id: 42,+ status: 'entered',+ $membership_version: '2026-10-20 10:00:00.123456',+ })expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)})diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.tsindex 12fbe14ec8d8..6da16031af5a 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts@@ -11,6 +11,11 @@ import { captureException } from '~/common/utils/posthog'import { HealthCheckResult, PluginsServerConfig } from '../../types'import { HogFlow } from '../schema/hogflow'+import { PRODUCER_VERSION_FORMAT } from '../services/cohort-membership/sweeper.service'+import {+ COHORT_MEMBERSHIP_CHANGED_EVENT,+ COHORT_MEMBERSHIP_VERSION_PROPERTY,+} from '../services/cohorts/cohort-membership-repository'import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals } from '../types'@@ -19,9 +24,6 @@ import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { CohortMembershipChange, CohortMembershipChangeSchema } from './cdp-cohort-membership.consumer'import { counterParseError } from './metrics'-// pinned: stored as the event of every cohort-triggered run, which workflow steps and logs read-export const COHORT_MEMBERSHIP_CHANGED_EVENT = '$cohort_membership_changed'-export const counterCohortMembershipTriggerSkipped = new Counter({name: 'cdp_cohort_membership_trigger_skipped',help: 'Membership changes the cohort trigger consumer did not turn into workflow runs, by reason.',@@ -206,7 +208,14 @@ export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {globals.event = {...globals.event,event: COHORT_MEMBERSHIP_CHANGED_EVENT,- properties: { cohort_id: change.cohort_id, status: change.status },+ properties: {+ cohort_id: change.cohort_id,+ status: change.status,+ // An off-format stamp can't be bound into the `::timestamp` comparison.+ ...(change.last_updated && PRODUCER_VERSION_FORMAT.test(change.last_updated)+ ? { [COHORT_MEMBERSHIP_VERSION_PROPERTY]: change.last_updated }+ : {}),+ },}events.push(globals)})diff --git a/nodejs/src/cdp/services/cohorts/cohort-membership-repository.ts b/nodejs/src/cdp/services/cohorts/cohort-membership-repository.tsindex 5f9d89d62221..edea4a482a3e 100644--- a/nodejs/src/cdp/services/cohorts/cohort-membership-repository.ts+++ b/nodejs/src/cdp/services/cohorts/cohort-membership-repository.ts@@ -1,3 +1,9 @@+// pinned: stored as the event of every cohort-triggered run, which workflow steps and logs read+export const COHORT_MEMBERSHIP_CHANGED_EVENT = '$cohort_membership_changed'++// The run event property that carries the version stamp of the change that started a cohort-triggered run.+export const COHORT_MEMBERSHIP_VERSION_PROPERTY = '$membership_version'+export interface CohortMembershipRepository {/*** The full set of cohort ids the person is currently a member of. Deliberately no@@ -5,4 +11,21 @@ export interface CohortMembershipRepository {* answer non-member.*/getMemberCohortIds(teamId: number, personUuid: string): Promise<number[]>++ /**+ * The person's stored row for one cohort, or null when the pipeline never wrote one.+ * `caughtUp` says whether the row's version stamp is at least `sinceVersion`. It is null when+ * there is nothing to compare: no `sinceVersion`, or a row the writer stored without a stamp.+ */+ getCohortMembership(+ teamId: number,+ personUuid: string,+ cohortId: number,+ sinceVersion?: string+ ): Promise<StoredCohortMembership | null>+}++export interface StoredCohortMembership {+ inCohort: boolean+ caughtUp: boolean | null}diff --git a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.ts b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.tsindex aea42ae7910d..f2f4e8de803c 100644--- a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.ts+++ b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.test.ts@@ -59,6 +59,37 @@ describe('PostgresCohortMembershipRepository', () => {expect(result).toEqual([])})+ it.each([+ ['in the cohort', 101, undefined, { inCohort: true, caughtUp: null }],+ ['out of the cohort', 102, undefined, { inCohort: false, caughtUp: null }],+ ['without a row in the cohort', 105, undefined, null],+ ['in the cohort only for another team', 103, undefined, null],+ ['whose row is at the asked version', 102, '2026-10-20 10:00:00.000000', { inCohort: false, caughtUp: true }],+ [+ 'whose row is older than the asked version',+ 102,+ '2026-10-20 10:00:00.000001',+ { inCohort: false, caughtUp: false },+ ],+ ['whose row has no version stamp', 101, '2026-10-20 10:00:00.000000', { inCohort: true, caughtUp: null }],+ ])('reads one cohort membership for a person %s', async (_name, cohortId, sinceVersion, expected) => {+ const teamId = 2+ const personUuid = new UUIDT().toString()+ await insertCohortMemberships(postgres, [+ { team_id: teamId, cohort_id: 101, person_id: personUuid, in_cohort: true },+ {+ team_id: teamId,+ cohort_id: 102,+ person_id: personUuid,+ in_cohort: false,+ version: '2026-10-20 10:00:00.000000',+ },+ { team_id: teamId + 1, cohort_id: 103, person_id: personUuid, in_cohort: true },+ ])++ expect(await repository.getCohortMembership(teamId, personUuid, cohortId, sinceVersion)).toEqual(expected)+ })+it('rejects with a retriable timeout error when the lookup hangs', async () => {jest.useFakeTimers()try {diff --git a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.ts b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.tsindex bd9a9f09d4c5..8fcacc13da4f 100644--- a/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.ts+++ b/nodejs/src/cdp/services/cohorts/postgres-cohort-membership-repository.ts@@ -2,7 +2,7 @@ import { Counter } from 'prom-client'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'-import { CohortMembershipRepository } from './cohort-membership-repository'+import { CohortMembershipRepository, StoredCohortMembership } from './cohort-membership-repository'const cohortMembershipLookupsCounter = new Counter({name: 'cdp_cohort_membership_lookups_total',@@ -28,18 +28,50 @@ export class PostgresCohortMembershipRepository implements CohortMembershipRepos) {}async getMemberCohortIds(teamId: number, personUuid: string): Promise<number[]> {- const queryPromise = this.postgres.query<{ cohort_id: string }>(- PostgresUse.BEHAVIORAL_COHORTS_RW,- `SELECT cohort_id- FROM cohort_membership- WHERE team_id = $1- AND person_id = $2- AND in_cohort = true`,- [teamId, personUuid],- 'fetchCohortMemberships'+ const result = await this.withTimeout(+ this.postgres.query<{ cohort_id: string }>(+ PostgresUse.BEHAVIORAL_COHORTS_RW,+ `SELECT cohort_id+ FROM cohort_membership+ WHERE team_id = $1+ AND person_id = $2+ AND in_cohort = true`,+ [teamId, personUuid],+ 'fetchCohortMemberships'+ )+ )++ // BIGINT columns come back from pg as strings+ return result.rows.map((row) => Number(row.cohort_id))+ }++ async getCohortMembership(+ teamId: number,+ personUuid: string,+ cohortId: number,+ sinceVersion?: string+ ): Promise<StoredCohortMembership | null> {+ const result = await this.withTimeout(+ this.postgres.query<{ in_cohort: boolean; caught_up: boolean | null }>(+ PostgresUse.BEHAVIORAL_COHORTS_RW,+ // Compared in SQL because pg parses the '-infinity' sentinel to a non-date value.+ `SELECT in_cohort,+ CASE WHEN $4::timestamp IS NULL OR version = '-infinity' THEN NULL+ ELSE version >= $4::timestamp END AS caught_up+ FROM cohort_membership+ WHERE team_id = $1+ AND cohort_id = $2+ AND person_id = $3`,+ [teamId, cohortId, personUuid, sinceVersion ?? null],+ 'fetchCohortMembership'+ ))+ const row = result.rows[0]+ return row ? { inCohort: row.in_cohort, caughtUp: row.caught_up } : null+ }- const result = await new Promise<Awaited<typeof queryPromise>>((resolve, reject) => {+ private withTimeout<T>(queryPromise: Promise<T>): Promise<T> {+ return new Promise<T>((resolve, reject) => {// The timer and the query race. The query's handlers stay registered after the timer// wins and fire when it settles late, so this flag stops the loser from recording a// second outcome and double-counting the lookup in the metric.@@ -73,8 +105,5 @@ export class PostgresCohortMembershipRepository implements CohortMembershipRepos})})-- // BIGINT columns come back from pg as strings- return result.rows.map((row) => Number(row.cohort_id))}}diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.tsindex 88a922bc2cfe..6b5fc992ed52 100644--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts@@ -4,7 +4,7 @@ import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'import { HOG_FILTERS_EXAMPLES } from '~/cdp/_tests/examples'import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'-import { CohortMembershipRepository } from '~/cdp/services/cohorts/cohort-membership-repository'+import { CohortMembershipRepository, StoredCohortMembership } from '~/cdp/services/cohorts/cohort-membership-repository'import { CyclotronJobInvocationHogFlow } from '~/cdp/types'import { createInvocationResult } from '~/cdp/utils/invocation-utils'@@ -197,6 +197,10 @@ describe('action.conditional_branch', () => {}return Promise.resolve(this.memberCohortIds)}++ getCohortMembership(): Promise<StoredCohortMembership | null> {+ return Promise.reject(new Error('not used by branches'))+ }}// Same shape the Python serializer emits: the authored properties plus compiled bytecode.@@ -372,6 +376,7 @@ describe('action.conditional_branch', () => {}const stubCohortMembershipRepository: CohortMembershipRepository = {getMemberCohortIds: () => Promise.resolve([]),+ getCohortMembership: () => Promise.resolve(null),}handler = new ConditionalBranchHandler(stubCohortMembershipRepository)counterHogflowWaitAdvancedAtMaxWait.reset()diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.tsindex d6119b28ef12..00157fe1948f 100644--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts@@ -41,12 +41,13 @@ export const counterHogflowRekeyWake = new Counter({labelNames: ['outcome'],})-// Outcome of a step whose cohort membership lookup failed. 'retried' re-runs the step after a backoff;+// Outcome of a failed cohort membership lookup. 'retried' re-runs the step after a backoff;// 'aborted' means every attempt failed and the run stopped. Sustained 'aborted' readings mean the// behavioral cohorts DB is unreachable from the workers, and every cohort branch is stopping runs.+// 'exit_check_skipped' is a cohort trigger's exit check that could not run, so the run carried on.export const counterHogflowCohortLookupFailure = new Counter({name: 'cdp_hogflow_cohort_lookup_failure_total',- help: 'Cohort membership lookups that failed in a conditional_branch or wait, by outcome.',+ help: 'Cohort membership lookups that failed in a conditional_branch, a wait or a cohort trigger exit check, by outcome.',labelNames: ['outcome'],})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 0c97d4225854..5f6df00a7697 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -176,6 +176,7 @@ describe('Hogflow Executor', () => {cohortMembershipRepository = {getMemberCohortIds: () => Promise.resolve([]),+ getCohortMembership: () => Promise.resolve(null),}executor = new HogFlowExecutorService(hogFlowFunctionsService,@@ -1534,6 +1535,148 @@ describe('Hogflow Executor', () => {`)})+ const caughtUp = { inCohort: false, caughtUp: true }+ it.each([+ [+ 'an entered trigger while the person is in the cohort',+ 'entered',+ { inCohort: true, caughtUp: null },+ false,+ false,+ null,+ true,+ ],+ [+ 'an entered trigger after the person left the cohort',+ 'entered',+ { inCohort: false, caughtUp: null },+ true,+ false,+ 'left cohort 42',+ true,+ ],+ [+ 'a left trigger after the person rejoined the cohort',+ 'left',+ { inCohort: true, caughtUp: null },+ true,+ false,+ 'rejoined cohort 42',+ true,+ ],+ // The person can leave before any read sees them in, so the version stamp is what shows freshness.+ [+ 'an entered trigger whose row is past the trigger version',+ 'entered',+ caughtUp,+ false,+ false,+ 'left cohort 42',+ true,+ ],+ // The trigger moved to this cohort while the run was parked, so no enrolling write is pending.+ [+ 'an entered trigger that changed cohort since the run enrolled',+ 'entered',+ { inCohort: false, caughtUp: false },+ false,+ false,+ 'left cohort 42',+ true,+ 7,+ ],+ // The membership writer lags the trigger consumer, so these reads can still show the old state.+ [+ 'an entered trigger the table has not caught up with',+ 'entered',+ { inCohort: false, caughtUp: null },+ false,+ false,+ null,+ undefined,+ ],+ [+ 'a left trigger whose row is older than the trigger version',+ 'left',+ { inCohort: false, caughtUp: false },+ false,+ false,+ null,+ undefined,+ ],+ ['a left trigger the table has no row for yet', 'left', null, false, false, null, undefined],+ ['a membership lookup that fails', 'entered', null, true, true, null, true],+ ])(+ 'cohort trigger exit check: %s',+ async (+ _name,+ transition,+ membership,+ confirmedBefore,+ lookupFails,+ expectedReason,+ confirmedAfter,+ enrolledCohortId = 42+ ) => {+ hogFlow.exit_condition = 'exit_on_trigger_not_matched'+ hogFlow.trigger = { type: 'cohort', cohort_id: 42, transition: transition as 'entered' | 'left' }+ const lookup = jest.spyOn(cohortMembershipRepository, 'getCohortMembership')+ if (lookupFails) {+ lookup.mockRejectedValue(new Error('behavioral cohorts db unreachable'))+ } else {+ lookup.mockResolvedValue(membership)+ }+ const invocation = createExampleHogFlowInvocation(hogFlow, {+ event: {+ ...createHogExecutionGlobals().event,+ event: '$cohort_membership_changed',+ properties: {+ name: 'John Doe',+ cohort_id: enrolledCohortId,+ status: transition,+ $membership_version: '2026-10-20 10:00:00.000000',+ },+ },+ })+ if (confirmedBefore) {+ invocation.state.cohortTriggerConfirmed = true+ }++ const result = await executor.execute(invocation)++ if (expectedReason) {+ expect(result.metrics.map((m) => m.metric_name)).toEqual(['early_exit'])+ expect(result.logs.map((log) => log.message)).toEqual([+ `Workflow exited early due to exit condition: exit_on_trigger_not_matched ([Person:person_id|John Doe] ${expectedReason})`,+ ])+ } else {+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('early_exit')+ }+ expect(lookup).toHaveBeenCalledWith(+ hogFlow.team_id,+ 'person_id',+ 42,+ enrolledCohortId === 42 ? '2026-10-20 10:00:00.000000' : undefined+ )+ expect(result.invocation.state.cohortTriggerConfirmed).toBe(confirmedAfter)+ }+ )++ it('does not look up cohort membership when the exit condition ignores the trigger', async () => {+ hogFlow.exit_condition = 'exit_only_at_end'+ hogFlow.trigger = { type: 'cohort', cohort_id: 42, transition: 'entered' }+ const lookup = jest.spyOn(cohortMembershipRepository, 'getCohortMembership').mockResolvedValue(null)+ const invocation = createExampleHogFlowInvocation(hogFlow, {+ event: { ...createHogExecutionGlobals().event, properties: { name: 'John Doe' } },+ })+ invocation.state.currentAction = { id: 'function_id_1', startedAtTimestamp: Date.now() }++ const result = await executor.execute(invocation)++ expect(result.metrics.map((m) => m.metric_name)).not.toContain('early_exit')+ expect(lookup).not.toHaveBeenCalled()+ })+it('should exit early if exit condition is exit_on_trigger_not_matched_or_conversion', async () => {// Setup: exit if person no longer matches trigger filters or person matches conversion filtershogFlow.exit_condition = 'exit_on_trigger_not_matched_or_conversion'diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 5111bd938bbe..a4df50f07fc4 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -23,13 +23,18 @@ import {} from '../../types'import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../../utils/hog-function-filtering'import { createInvocationResult } from '../../utils/invocation-utils'-import { CohortMembershipRepository } from '../cohorts/cohort-membership-repository'+import {+ COHORT_MEMBERSHIP_CHANGED_EVENT,+ COHORT_MEMBERSHIP_VERSION_PROPERTY,+ CohortMembershipRepository,+ StoredCohortMembership,+} from '../cohorts/cohort-membership-repository'import { HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'import { EmailValidationService } from '../messaging/email-validation.service'import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'import { CdpUsageReporterService } from '../usage/cdp-usage-reporter.service'import { ActionHandler } from './actions/action.interface'-import { ConditionalBranchHandler } from './actions/conditional_branch'+import { ConditionalBranchHandler, counterHogflowCohortLookupFailure } from './actions/conditional_branch'import { DelayHandler } from './actions/delay'import { ExitHandler } from './actions/exit.handler'import { HogFunctionHandler } from './actions/hog_function'@@ -64,6 +69,11 @@ const counterRedirectTargetMissing = new Counter({help: 'A redirect map entry pointed at an action missing from the live graph',})+const TRIGGER_MISMATCH_EXITS: ReadonlySet<string> = new Set([+ 'exit_on_trigger_not_matched',+ 'exit_on_trigger_not_matched_or_conversion',+])+export function createHogFlowInvocation(globals: HogFunctionInvocationGlobals,hogFlow: HogFlow,@@ -115,6 +125,7 @@ export class HogFlowExecutorService {private readonly actionHandlers: Record<HogFlowAction['type'], ActionHandler>private readonly duplicateObserver: HogFlowDuplicateObserverService | nullprivate readonly hogFlowFunctionsService: HogFlowFunctionsService+ private readonly cohortMembershipRepository: CohortMembershipRepositoryconstructor(hogFlowFunctionsService: HogFlowFunctionsService,@@ -127,6 +138,7 @@ export class HogFlowExecutorService {options: { awaitedStepsEnabled?: boolean } = {}) {this.hogFlowFunctionsService = hogFlowFunctionsService+ this.cohortMembershipRepository = cohortMembershipRepositorythis.duplicateObserver = duplicateObserver ?? nullconst hogFunctionHandler = new HogFunctionHandler(hogFlowFunctionsService,@@ -479,6 +491,64 @@ export class HogFlowExecutorService {return finishedWithoutError || delayScheduled || shouldAbortAfterError}+ /**+ * Whether the person still matches a cohort trigger: in the cohort for an "entered" trigger, out of it+ * for a "left" one. Undefined when there is no trustworthy answer, which leaves the run alone.+ *+ * The membership writer and the trigger consumer read each change independently, so the table can still+ * hold the state from before the change that started this run. A read counts only once the table has+ * caught up with that change.+ */+ private async matchesCohortTrigger(+ invocation: CyclotronJobInvocationHogFlow,+ trigger: { cohort_id: number; transition: 'entered' | 'left' }+ ): Promise<boolean | undefined> {+ const personUuid = invocation.person?.id ?? invocation.state.personId+ if (!personUuid) {+ return undefined+ }+ const enrolledBy = invocation.state.event?.properties+ // Only the change that enrolled the run can still be pending in the table. A run enrolled by another+ // cohort or transition, because the trigger changed while it was parked, has nothing to wait for.+ const enrolledByThisTrigger =+ invocation.state.event?.event === COHORT_MEMBERSHIP_CHANGED_EVENT &&+ enrolledBy?.cohort_id === trigger.cohort_id &&+ enrolledBy?.status === trigger.transition+ const triggerVersion = enrolledByThisTrigger ? enrolledBy?.[COHORT_MEMBERSHIP_VERSION_PROPERTY] : undefined+ let membership: StoredCohortMembership | null+ try {+ membership = await this.cohortMembershipRepository.getCohortMembership(+ invocation.hogFlow.team_id,+ personUuid,+ trigger.cohort_id,+ typeof triggerVersion === 'string' ? triggerVersion : undefined+ )+ } catch (error) {+ // No answer is not "no longer in the cohort", so the run carries on and the next wake checks again.+ counterHogflowCohortLookupFailure.labels({ outcome: 'exit_check_skipped' }).inc()+ logger.warn('HogFlowExecutorService: cohort membership lookup failed during the exit check', {+ hogFlowId: invocation.hogFlow.id,+ error: String(error),+ })+ return undefined+ }++ const inCohort = membership?.inCohort ?? null+ const rowMatches = trigger.transition === 'entered' ? inCohort === true : inCohort === false+ // The row's version stamp shows whether the writer has applied the change that started this run.+ // Without a stamp, only a read that matches the trigger shows it, because the change flips the state.+ const caughtUp =+ !enrolledByThisTrigger ||+ invocation.state.cohortTriggerConfirmed === true ||+ (membership?.caughtUp ?? rowMatches)+ if (!caughtUp) {+ return undefined+ }+ invocation.state.cohortTriggerConfirmed = true+ // Once the table has caught up, a missing row means out of the cohort.+ return trigger.transition === 'entered' ? inCohort === true : inCohort !== true+ }+/*** Determines if the invocation should exit early based on the hogflow's exit condition*/@@ -503,6 +573,9 @@ export class HogFlowExecutorService {})triggerMatch = filterResult.match}+ if (hogFlow.trigger.type === 'cohort' && TRIGGER_MISMATCH_EXITS.has(hogFlow.exit_condition)) {+ triggerMatch = await this.matchesCohortTrigger(invocation, hogFlow.trigger)+ }if (hogFlow.conversion?.filters?.length && person) {if (hogFlow.conversion.bytecode?.length) {const filterResult = await filterFunctionInstrumented({@@ -560,6 +633,11 @@ export class HogFlowExecutorService {break}+ if (shouldExit && hogFlow.trigger.type === 'cohort' && triggerMatch === false) {+ const movement = hogFlow.trigger.transition === 'entered' ? 'left' : 'rejoined'+ exitReason = `[Person:${invocation.person?.id ?? 'unknown'}|${invocation.person?.name ?? 'unknown'}] ${movement} cohort ${hogFlow.trigger.cohort_id}`+ }+if (shouldExit) {earlyExitResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation)earlyExitResult.finished = truediff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 84024f82610f..b06a005c0ced 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -544,6 +544,9 @@ export type HogFlowInvocationContext = {// Set by the subscription matcher consumer when an incoming event matched the// workflow's event-based conversion goals. shouldExitEarly reads and clears it.conversionMatched?: boolean+ // Set once the membership table has caught up with the change that started a cohort-triggered run.+ // The writer that fills the table lags the trigger, so a mismatch read before this means a pending write.+ cohortTriggerConfirmed?: boolean// Once-per-run guard for the property-based conversion metric. Executor-owned:// shouldExitEarly runs on every resume, so without this a persistently-true// conversion filter would emit a `conversion` metric on every step. Event-baseddiff --git a/products/workflows/backend/facade/workflows.py b/products/workflows/backend/facade/workflows.pyindex 089ac95c5acb..f2939fa994a9 100644--- a/products/workflows/backend/facade/workflows.py+++ b/products/workflows/backend/facade/workflows.py@@ -10,6 +10,7 @@ from products.workflows.backend.models.hog_flow.hog_flow import (SUPPORTED_ACTION_TYPES,TRIGGER_TYPES,WORKFLOW_SAFE_INTERNAL_EVENTS,+ exit_condition_that_runs,literal_static_cohort_id,static_cohort_ids,)@@ -47,4 +48,5 @@ __all__ = ["list_workflows","workflow_from_fields","workflow_publish_impact",+ "exit_condition_that_runs",]diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex d92884eac16f..4689448e5185 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -146,6 +146,25 @@ def static_cohort_ids(actions: Any) -> set[int]:return cohort_ids+# Trigger types the executor re-checks before each step: an event trigger against its filters, and a+# cohort trigger against the person's membership in its cohort.+RECHECKED_TRIGGER_TYPES: Final[frozenset[str]] = frozenset({"event", "cohort"})+++def exit_condition_that_runs(trigger_type: str | None, exit_condition: str | None) -> str | None:+ """The exit condition a run of this trigger actually follows.++ On a trigger the executor cannot re-check, "exit when the trigger no longer matches" never fires.+ """+ if trigger_type in RECHECKED_TRIGGER_TYPES:+ return exit_condition+ if exit_condition == HogFlowExitCondition.TRIGGER_NOT_MATCHED:+ return HogFlowExitCondition.ONLY_AT_END+ if exit_condition == HogFlowExitCondition.TRIGGER_NOT_MATCHED_OR_CONVERSION:+ return HogFlowExitCondition.CONVERSION+ return exit_condition++def hog_flow_origin_product_choices() -> list[tuple[str, str | Promise]]:# Callable so growing the enum doesn't generate a no-op migration.return list(HogFlow.OriginProduct.choices)diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 3487fde25563..cf9605755620 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -299,6 +299,7 @@ from products.workflows.backend.facade.workflows import (WORKFLOW_FIELD_FILTER_PARAMS,WORKFLOW_SAFE_INTERNAL_EVENTS,WORKFLOW_TYPES,+ exit_condition_that_runs,get_team_workflow_edit_state,get_workflow,get_workflow_edit_state,@@ -3159,7 +3160,10 @@ class HogFlowSerializer(HogFlowMinimalSerializer):"exit_only_at_end: only at exit node (default). ""exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). ""exit_on_trigger_not_matched: also when trigger filter stops matching. "- "exit_on_trigger_not_matched_or_conversion: both (needs 'conversion')."+ "exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). "+ "Only event and cohort triggers are re-checked, so on any other trigger these two are stored as "+ "exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person "+ "leaves the cohort (or rejoins it, for a 'left' trigger)."),)email_sending_rate_limit = HogFlowEmailSendingRateLimitSerializer(@@ -3516,6 +3520,14 @@ class HogFlowSerializer(HogFlowMinimalSerializer):data["trigger"] = trigger_actions[0]["config"]+ # Store the exit condition that actually runs rather than reject one that never fires. The builder+ # shows the exit options only for event triggers, so a value kept from before a trigger change has+ # no control the author could use to clear it, and a rejection would block every save.+ exit_condition = data.get("exit_condition", instance.exit_condition if instance else None)+ runs = exit_condition_that_runs(data["trigger"].get("type"), exit_condition)+ if runs != exit_condition:+ data["exit_condition"] = runs+# Some triggers are person-less ("row-scoped"): a synced warehouse row, a materialized view row,# and a Slack poster are all things no PostHog person is attached to. Person-dependent steps and# person-aware exit conditions would silently assume person data, so we block them here — the@@ -5377,6 +5389,7 @@ class HogFlowViewSet(includes_staged_draft=bool(self.request.data.get("includes_staged_draft"))and WRITABLE_DRAFT_CONTENT_FIELDS <= self.request.data.keys(),validated_status=serializer.instance.status,+ requested_exit_condition=serializer.initial_data.get("exit_condition"),)except WorkflowStale:raise StaleWorkflowUpdateError()diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.pyindex 97599dc6573f..782f63e410a0 100644--- a/products/workflows/backend/services/hog_flow_writes.py+++ b/products/workflows/backend/services/hog_flow_writes.py@@ -17,7 +17,13 @@ from products.workflows.backend.facade.contracts import (WorkflowWriteResult,)from products.workflows.backend.facade.enums import HogFlowScheduleStatus-from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, ROW_SCOPED_TRIGGER_TYPES, HogFlow+from products.workflows.backend.models.hog_flow.hog_flow import (+ BILLABLE_ACTION_TYPES,+ RECHECKED_TRIGGER_TYPES,+ ROW_SCOPED_TRIGGER_TYPES,+ HogFlow,+ exit_condition_that_runs,+)from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.services.action_redirects import compute_action_redirectsfrom products.workflows.backend.services.hog_flow_content import DRAFT_CONTENT_FIELDS, snapshot_flow_content@@ -147,7 +153,9 @@ def save_validated_workflow(*, team_id: int, hog_flow_id: UUID, validated_data:_save_live(HogFlow.objects.select_for_update().get(team_id=team_id, pk=hog_flow_id), validated_data)-def _derive_from_locked_graph(locked: HogFlow, validated_data: dict) -> dict:+def _derive_from_locked_graph(+ locked: HogFlow, validated_data: dict, requested_exit_condition: Optional[str] = None+) -> dict:# HogFlowSerializer.validate derives trigger, billable_action_types and exit_condition from the# actions it read before the row lock. A write without actions keeps the locked row's actions, and a# concurrent graph write can change those actions before the lock. Derive these fields again from the@@ -162,10 +170,22 @@ def _derive_from_locked_graph(locked: HogFlow, validated_data: dict) -> dict:if "exit_condition" in derived:# validate forces exit_only_at_end when the trigger it read is row-scoped. Apply that rule to the# locked trigger instead. When only the old trigger forced the value, keep the locked row's value.- if (derived.get("trigger") or {}).get("type") in ROW_SCOPED_TRIGGER_TYPES:+ locked_type = (derived.get("trigger") or {}).get("type")+ read_type = (validated_data.get("trigger") or {}).get("type")+ if locked_type in ROW_SCOPED_TRIGGER_TYPES:derived["exit_condition"] = HogFlow.ExitCondition.ONLY_AT_END- elif (validated_data.get("trigger") or {}).get("type") in ROW_SCOPED_TRIGGER_TYPES:+ elif requested_exit_condition is not None:+ # validate may have rewritten the value the request set for the read trigger. Apply the rule to+ # the requested value against the locked trigger instead, so the request is not lost.+ derived["exit_condition"] = exit_condition_that_runs(locked_type, requested_exit_condition)+ elif read_type in ROW_SCOPED_TRIGGER_TYPES or (+ locked_type in RECHECKED_TRIGGER_TYPES and read_type not in RECHECKED_TRIGGER_TYPES+ ):+ # The read trigger may have rewritten the value, and the locked trigger can run any exit+ # condition, so keep the locked row's value instead.del derived["exit_condition"]+ else:+ derived["exit_condition"] = exit_condition_that_runs(locked_type, derived["exit_condition"])if "billable_action_types" in derived:derived["billable_action_types"] = sorted({action.get("type", "") for action in actions if action.get("type") in BILLABLE_ACTION_TYPES}@@ -321,6 +341,7 @@ def update_workflow(includes_staged_draft: bool,validated_status: str,keeps_live_sensitivity: bool = True,+ requested_exit_condition: Optional[str] = None,) -> WorkflowWriteResult:# Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.# If the stored row is strictly newer, another channel (a second UI tab, MCP, or the API) wrote in@@ -387,7 +408,7 @@ def update_workflow(raise WorkflowStale()_save_live(instance, remaining)else:- validated_data = _derive_from_locked_graph(before_update, validated_data)+ validated_data = _derive_from_locked_graph(before_update, validated_data, requested_exit_condition)if keeps_live_sensitivity:validated_data = _keep_live_sensitivity(before_update, validated_data)_refresh_action_redirects(instance, before_update, validated_data.get("actions"))diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex a9cb7643c802..a290e34f2455 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -2117,11 +2117,16 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/hog_flows",- self._cohort_trigger_flow({"cohort_id": cohort.id, "transition": transition}),+ {+ **self._cohort_trigger_flow({"cohort_id": cohort.id, "transition": transition}),+ "exit_condition": "exit_on_trigger_not_matched",+ },)assert response.status_code == 201, response.json()assert response.json()["trigger"] == {"type": "cohort", "cohort_id": cohort.id, "transition": transition}+ # The executor re-checks cohort membership, so the exit condition is kept rather than rewritten.+ assert response.json()["exit_condition"] == "exit_on_trigger_not_matched"@parameterized.expand([@@ -5131,6 +5136,28 @@ class TestHogFlowAPI(APIBaseTest):assert flow.trigger == concurrent_triggerassert flow.billable_action_types == []+ @parameterized.expand(+ [+ ("schedule_trigger_not_matched", "schedule", "exit_on_trigger_not_matched", "exit_only_at_end"),+ (+ "schedule_trigger_not_matched_or_conversion",+ "schedule",+ "exit_on_trigger_not_matched_or_conversion",+ "exit_on_conversion",+ ),+ ("schedule_conversion", "schedule", "exit_on_conversion", "exit_on_conversion"),+ ("event_trigger_not_matched", "event", "exit_on_trigger_not_matched", "exit_on_trigger_not_matched"),+ ]+ )+ def test_hog_flow_stores_the_exit_condition_its_trigger_can_run(self, _name, trigger_type, sent, stored):+ flow = self._make_delay_flow({"delay_duration": "5m"}, status="draft")+ if trigger_type == "schedule":+ flow["actions"][0]["config"] = {"type": "schedule"}+ flow["exit_condition"] = sent+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", flow)+ assert response.status_code == 201, response.json()+ assert response.json()["exit_condition"] == stored+@parameterized.expand([(@@ -5149,10 +5176,50 @@ class TestHogFlowAPI(APIBaseTest):{"name": "Renamed"},"exit_on_conversion",),+ (+ "locked_trigger_stops_being_an_event_trigger",+ "event",+ "schedule",+ "exit_on_trigger_not_matched",+ {"exit_condition": "exit_on_trigger_not_matched"},+ "exit_only_at_end",+ ),+ (+ "explicit_exit_condition_survives_the_locked_trigger_becoming_an_event_trigger",+ "schedule",+ "event",+ "exit_on_trigger_not_matched",+ {"exit_condition": "exit_only_at_end"},+ "exit_only_at_end",+ ),+ (+ "explicit_trigger_exit_the_read_trigger_rewrote_runs_on_the_locked_event_trigger",+ "schedule",+ "event",+ "exit_on_conversion",+ {"exit_condition": "exit_on_trigger_not_matched"},+ "exit_on_trigger_not_matched",+ ),+ (+ "locked_trigger_becomes_an_event_trigger",+ "schedule",+ "event",+ "exit_on_trigger_not_matched",+ {"name": "Renamed"},+ "exit_on_trigger_not_matched",+ "exit_on_trigger_not_matched",+ ),])def test_update_without_actions_derives_exit_condition_from_the_locked_trigger(- self, _name, initial_trigger_type, concurrent_trigger_type, concurrent_exit_condition, payload, expected+ self,+ _name,+ initial_trigger_type,+ concurrent_trigger_type,+ concurrent_exit_condition,+ payload,+ expected,+ stored_exit_condition=None,):trigger_configs = {"event": {@@ -5164,6 +5231,7 @@ class TestHogFlowAPI(APIBaseTest):"table_name": "postgres.table_1","filters": {"properties": []},},+ "schedule": {"type": "schedule"},}trigger_action = {"id": "trigger_node", "name": "trigger_1", "type": "trigger"}response = self.client.post(@@ -5175,6 +5243,9 @@ class TestHogFlowAPI(APIBaseTest):)assert response.status_code == 201, response.json()flow_id = response.json()["id"]+ if stored_exit_condition:+ # A row saved before non-event triggers stored the exit condition they can run.+ HogFlow.objects.filter(pk=flow_id).update(exit_condition=stored_exit_condition)def update_after_concurrent_trigger_change(**kwargs):HogFlow.objects.filter(pk=flow_id).update(diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsxindex 6954609953e2..c69c1e675773 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx@@ -93,4 +93,5 @@ registerTriggerType({},ConfigComponent: StepTriggerConfigurationCohort,frequencyOptions: PERSON_FREQUENCY_OPTIONS,+ showExitConditions: true,})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.tsindex fd25a06fc4d8..16f76c92b8fc 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts@@ -51,6 +51,8 @@ export type TriggerTypeDefinition = {frequencyOptions?: TriggerFrequencyOption[]/** Copy under the "Frequency" heading; defaults to the generic person-centric wording */frequencyDescription?: string+ /** Show the exit condition section. Only for triggers the executor re-checks before each step. */+ showExitConditions?: boolean}const triggerTypeDefinitions: TriggerTypeDefinition[] = []diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex ade969814fd5..c9b1dbb47352 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -360,6 +360,12 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }/></>) : null}+ {registeredMatch.showExitConditions ? (+ <>+ <LemonDivider />+ <ExitConditionSection />+ </>+ ) : null}</>) : node.data.config.type === 'event' ? (<StepTriggerConfigurationEvents action={node.data} config={node.data.config} />@@ -1031,6 +1037,13 @@ function SendingRateLimitSection(): JSX.Element | null {function ExitConditionSection(): JSX.Element {const { setWorkflowValue } = useActions(workflowLogic)const { workflow } = useValues(workflowLogic)+ const trigger = workflow.trigger+ const triggerMismatch =+ trigger?.type === 'cohort'+ ? trigger.transition === 'left'+ ? 'they rejoin the cohort'+ : 'they leave the cohort'+ : 'trigger filters no longer match'return (<div className="flex flex-col flex-1 w-full py-2">@@ -1051,7 +1064,7 @@ function ExitConditionSection(): JSX.Element {},{value: 'exit_on_trigger_not_matched',- label: 'Exit when trigger filters no longer match',+ label: `Exit when ${triggerMismatch}`,},{value: 'exit_on_conversion',@@ -1059,7 +1072,7 @@ function ExitConditionSection(): JSX.Element {},{value: 'exit_on_trigger_not_matched_or_conversion',- label: 'Exit when trigger filters no longer match, or when conversion goal is met',+ label: `Exit when ${triggerMismatch}, or when conversion goal is met`,},]}/>diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex eae7b7674733..5c3d0c4f4c05 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -697,7 +697,7 @@ export interface HogFlowApi {trigger_masking?: HogFlowMaskingApi | null/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversionApi | null- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matched@@ -805,7 +805,7 @@ export interface HogFlowUpdateApi {trigger_masking?: HogFlowMaskingApi | null/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversionApi | null- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matched@@ -913,7 +913,7 @@ export interface PatchedHogFlowUpdateApi {trigger_masking?: HogFlowMaskingApi | null/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversionApi | null- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matcheddiff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 4f26b39f0f05..ca6f2eb96e03 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -665,7 +665,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([@@ -1072,7 +1072,7 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([@@ -1486,7 +1486,7 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([@@ -2157,7 +2157,7 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([@@ -3009,7 +3009,7 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c42bad04cf74..6564ba344d06 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -56237,7 +56237,7 @@ export namespace Schemas {trigger_masking?: HogFlowMasking | null;/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversion | null;- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matched@@ -56850,7 +56850,7 @@ export namespace Schemas {trigger_masking?: HogFlowMasking | null;/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversion | null;- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matched@@ -83567,7 +83567,7 @@ export namespace Schemas {trigger_masking?: HogFlowMasking | null;/** Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side. */conversion?: HogFlowConversion | null;- /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').+ /** exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).** * `exit_on_conversion` - Conversion* * `exit_on_trigger_not_matched` - Trigger Not Matcheddiff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex d49a50a76e7f..c2df918743b9 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -238,7 +238,7 @@ export const HogFlowsCreateBody = () => zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([@@ -650,7 +650,7 @@ export const HogFlowsPartialUpdateBody = () => zod).optional().describe(- "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"+ "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"),email_sending_rate_limit: zod.union([diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.jsonindex a1a871b72d7b..06ca3b6b5085 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json@@ -520,7 +520,7 @@"description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."},"exit_condition": {- "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",+ "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End","enum": ["exit_on_conversion","exit_on_trigger_not_matched",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex a1a871b72d7b..06ca3b6b5085 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json@@ -520,7 +520,7 @@"description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."},"exit_condition": {- "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",+ "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End","enum": ["exit_on_conversion","exit_on_trigger_not_matched",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.jsonindex 1edeb4bc77ec..5a7b7f9c4d8f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json@@ -150,7 +150,7 @@"description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."},"exit_condition": {- "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",+ "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion'). Only event and cohort triggers are re-checked, so on any other trigger these two are stored as exit_only_at_end and exit_on_conversion. A cohort trigger no longer matches once the person leaves the cohort (or rejoins it, for a 'left' trigger).\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End","enum": ["exit_on_conversion","exit_on_trigger_not_matched",