: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
fix(workflows): apply trigger_masking to batch-triggered hog flow runs (#78061)
posthog[bot]268d4c7251b5
diff --git a/nodejs/src/cdp/_tests/builders/hogflow.builder.ts b/nodejs/src/cdp/_tests/builders/hogflow.builder.tsindex 48afd9ad7d87..3cda12b0b54d 100644--- a/nodejs/src/cdp/_tests/builders/hogflow.builder.ts+++ b/nodejs/src/cdp/_tests/builders/hogflow.builder.ts@@ -124,6 +124,11 @@ export class FixtureHogFlowBuilder {return this}+ withTriggerMasking(triggerMasking: HogFlow['trigger_masking']): this {+ this.hogFlow.trigger_masking = triggerMasking+ return this+ }+withSimpleWorkflow({ trigger }: { trigger?: HogFlow['trigger'] } = {}): this {return this.withWorkflow({actions: {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.tsindex 7fd8629bc847..ada63ebac8e8 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts@@ -1,18 +1,22 @@+import { HogFlow } from '~/cdp/schema/hogflow'import { Team } from '~/types'+import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'+import { HOG_FLOW_MASK_EXAMPLES } from '../_tests/examples'import { CyclotronJobInvocationHogFlow } from '../types'import { buildAccountHogFlowInvocation } from './cdp-cyclotron-worker-batch-resolve.consumer'describe('buildAccountHogFlowInvocation', () => {const team = { id: 123, name: 'Test team' } as Team+ // A non-default version, so the flowVersion assertion can't pass by accident.+ const hogFlow: HogFlow = { ...new FixtureHogFlowBuilder().withTeamId(team.id).build(), version: 4 }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',- flowVersion: 4,+ hogFlow,externalId: 'acme-1',groupType: 'customer',defaultVariables: { greeting: 'hi' },@@ -37,4 +41,27 @@ describe('buildAccountHogFlowInvocation', () => {expect(invocation.queue).toEqual('hogflow')expect((invocation as any).person).toBeUndefined()})++ // HogMaskerService.filterByMasking() only recognizes an invocation as a hog flow+ // invocation (and applies trigger_masking) when it carries a `hogFlow` object — if this+ // regresses, trigger_masking silently stops applying to batch-triggered runs again.+ it('attaches the hogFlow so trigger_masking can be applied by the batch resolver', () => {+ const maskedHogFlow: HogFlow = new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withTriggerMasking(HOG_FLOW_MASK_EXAMPLES.everyTime.trigger_masking)+ .build()++ const invocation = buildAccountHogFlowInvocation({+ siteUrl: 'https://us.posthog.com',+ parentRunId: 'batch-job-1',+ team,+ hogFlow: maskedHogFlow,+ externalId: 'acme-1',+ groupType: 'customer',+ defaultVariables: {},+ })++ expect(invocation.hogFlow).toBe(maskedHogFlow)+ expect(invocation.hogFlow.trigger_masking).toEqual(HOG_FLOW_MASK_EXAMPLES.everyTime.trigger_masking)+ })})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 97f24d1e75ec..53fed980a58d 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@@ -1,6 +1,7 @@import { DateTime } from 'luxon'import { Counter } from 'prom-client'+import { HogFlow } from '~/cdp/schema/hogflow'import { InternalFetchService } from '~/common/services/internal-fetch'import { instrumentFn } from '~/common/tracing/tracing-utils'import { logger, serializeError } from '~/common/utils/logger'@@ -17,7 +18,7 @@ import {} from '../services/hogflows/batch-resolver.types'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 { CyclotronJobInvocationHogFlow } from '../types'import {convertAccountBatchHogFlowRequestToHogFunctionInvocationGlobals,convertBatchHogFlowRequestToHogFunctionInvocationGlobals,@@ -263,35 +264,38 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServeconst pageTruncated = eligibleIds.length < page.ids.lengthconst defaultVariables = mergeDefaultVariables(hogFlow.variables, state.variables)- const children: CyclotronV2JobInit[] = eligibleIds.map((id) =>- invocationToV2JobInit(- isAccountAudience- ? buildAccountHogFlowInvocation({- siteUrl: this.config.SITE_URL,- parentRunId: state.batchJobId,- team,- hogFlowId: hogFlow.id,- flowVersion: hogFlow.version,- externalId: id,- groupType: page.accountGroupType ?? '',- defaultVariables,- })- : buildHogFlowInvocation({- siteUrl: this.config.SITE_URL,- parentRunId: state.batchJobId,- team,- hogFlowId: hogFlow.id,- flowVersion: hogFlow.version,- personId: id,- defaultVariables,- })- )+ const builtInvocations: CyclotronJobInvocationHogFlow[] = eligibleIds.map((id) =>+ isAccountAudience+ ? buildAccountHogFlowInvocation({+ siteUrl: this.config.SITE_URL,+ parentRunId: state.batchJobId,+ team,+ hogFlow,+ externalId: id,+ groupType: page.accountGroupType ?? '',+ defaultVariables,+ })+ : buildHogFlowInvocation({+ siteUrl: this.config.SITE_URL,+ parentRunId: state.batchJobId,+ team,+ hogFlow,+ personId: id,+ defaultVariables,+ }))+ // Batch-built invocations skip the event-triggered pipeline entirely, so+ // trigger_masking has to be applied here explicitly — otherwise a workflow+ // with a masking TTL re-enrolls the same audience on every scheduled run.+ const { masked, notMasked, release } = await this.hogMasker.filterByMasking(builtInvocations)++ const children: CyclotronV2JobInit[] = notMasked.map((invocation) => invocationToV2JobInit(invocation))+const newState: BatchResolverState = {...state,cursor: page.cursor,- totalEnqueued: state.totalEnqueued + children.length,+ totalEnqueued: state.totalEnqueued + eligibleIds.length,pagesProcessed: state.pagesProcessed + 1,attempts: 0, // reset on successful page commit}@@ -299,14 +303,38 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServenewState.pendingTerminal = 'completed'}- await job.bulkCreateAndCheckIn({- newJobs: children,- selfDisposition: {- kind: 'reschedule',- scheduledAt: new Date(),- state: serializeResolverState(newState),- },- })+ try {+ await job.bulkCreateAndCheckIn({+ newJobs: children,+ selfDisposition: {+ kind: 'reschedule',+ scheduledAt: new Date(),+ state: serializeResolverState(newState),+ },+ })+ } catch (err) {+ // The mask claims are already in Redis, but the page didn't commit — the+ // stall-recovery replay of this cursor would see the whole page as masked+ // and silently drop it. Undo the claims so the replay re-enrolls cleanly.+ await release()+ throw err+ }++ // Queued only after a successful commit: a failed page is replayed, so metrics+ // emitted for it would double-count once the replay re-evaluates masking.+ if (masked.length) {+ this.hogFunctionMonitoringService.queueAppMetrics(+ masked.map((item) => ({+ team_id: item.teamId,+ app_source_id: item.functionId,+ metric_kind: 'other',+ metric_name: 'masked',+ count: 1,+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },+ })),+ 'hog_flow'+ )+ }if (pageTruncated) {this.emitTruncationLog(newState)@@ -316,7 +344,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServelogger.info('📝',- `${this.name} - processed page for batch ${state.batchJobId}: ${children.length} ${isAccountAudience ? 'accounts' : 'persons'} (${newState.totalEnqueued} total, ${newState.pagesProcessed} pages)`+ `${this.name} - processed page for batch ${state.batchJobId}: ${children.length} ${isAccountAudience ? 'accounts' : 'persons'} enqueued, ${masked.length} masked (${newState.totalEnqueued} total resolved, ${newState.pagesProcessed} pages)`)}@@ -473,12 +501,11 @@ export function buildAccountHogFlowInvocation(params: {siteUrl: stringparentRunId: stringteam: Team- hogFlowId: string- flowVersion: number+ hogFlow: HogFlowexternalId: stringgroupType: stringdefaultVariables: Record<string, unknown>-}): CyclotronJobInvocation {+}): CyclotronJobInvocationHogFlow {const invocationGlobals = convertAccountBatchHogFlowRequestToHogFunctionInvocationGlobals({team: params.team,externalId: params.externalId,@@ -497,16 +524,17 @@ export function buildAccountHogFlowInvocation(params: {variables: params.defaultVariables,// Same reason as createHogFlowInvocation: a broadcast's conversions arrive long after// the send, so they attribute to the version that sent, not the one live by then.- flowVersion: params.flowVersion,+ flowVersion: params.hogFlow.version,} as any,teamId: params.team.id,- functionId: params.hogFlowId,+ functionId: params.hogFlow.id,+ hogFlow: params.hogFlow,parentRunId: params.parentRunId,filterGlobals,queue: 'hogflow' as const,queuePriority: 1,queueScheduledAt: DateTime.now(),- } as CyclotronJobInvocation+ } as CyclotronJobInvocationHogFlow}// Mirrors `createHogFlowInvocation` from the legacy Kafka consumer so children@@ -515,11 +543,10 @@ function buildHogFlowInvocation(params: {siteUrl: stringparentRunId: stringteam: Team- hogFlowId: string- flowVersion: number+ hogFlow: HogFlowpersonId: stringdefaultVariables: Record<string, unknown>-}): CyclotronJobInvocation {+}): CyclotronJobInvocationHogFlow {const invocationGlobals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({team: params.team,personId: params.personId,@@ -537,15 +564,16 @@ function buildHogFlowInvocation(params: {variables: params.defaultVariables,// Same reason as createHogFlowInvocation: a broadcast's conversions arrive days after// the send, so they have to attribute to the version that sent, not the one live then.- flowVersion: params.flowVersion,+ flowVersion: params.hogFlow.version,} as any,teamId: params.team.id,- functionId: params.hogFlowId,+ functionId: params.hogFlow.id,+ hogFlow: params.hogFlow,parentRunId: params.parentRunId,person: invocationGlobals.person as any,filterGlobals,queue: 'hogflow' as const,queuePriority: 1,queueScheduledAt: DateTime.now(),- } as CyclotronJobInvocation+ } as CyclotronJobInvocationHogFlow}diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.tsindex 847b81b33a61..02cbc73091c0 100644--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts@@ -65,7 +65,9 @@ describe('HogFlowInvocationPipeline', () => {} as unknown as jest.Mocked<HogWatcherService>hogMasker = {- filterByMasking: jest.fn((invocations) => Promise.resolve({ masked: [], notMasked: invocations })),+ filterByMasking: jest.fn((invocations) =>+ Promise.resolve({ masked: [], notMasked: invocations, release: async () => {} })+ ),} as unknown as jest.Mocked<HogMaskerService>hogFunctionMonitoringService = {@@ -188,7 +190,7 @@ describe('HogFlowInvocationPipeline', () => {hogFlowExecutor.buildHogFlowInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })hogWatcher.getEffectiveStates.mockResolvedValue({ [inv.hogFlow.id]: { state: HogWatcherState.healthy } } as any)rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])- hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [] })+ hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [], release: async () => {} })const result = await pipeline.buildInvocations([makeGlobals()])diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.tsindex 26f79c584c39..f40f60dc75d5 100644--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts@@ -76,7 +76,9 @@ describe('HogFunctionInvocationPipeline', () => {} as unknown as jest.Mocked<HogWatcherService>hogMasker = {- filterByMasking: jest.fn((invocations) => Promise.resolve({ masked: [], notMasked: invocations })),+ filterByMasking: jest.fn((invocations) =>+ Promise.resolve({ masked: [], notMasked: invocations, release: async () => {} })+ ),} as unknown as jest.Mocked<HogMaskerService>hogFunctionMonitoringService = {@@ -202,7 +204,7 @@ describe('HogFunctionInvocationPipeline', () => {jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])- hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [] })+ hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [], release: async () => {} })const result = await pipeline.buildInvocations([makeGlobals()], {hogTypes: ['destination'],diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.test.tsindex 745948c705c0..19ce2676c806 100644--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.test.ts@@ -447,6 +447,26 @@ describe('HogMasker', () => {expect(res.masked).toHaveLength(2)})+ it('release() undoes exactly the claims a call made, so a replay is not masked', async () => {+ const first = await masker.filterByMasking([+ createExampleHogFlowInvocation(hogFlowEvery),+ createExampleHogFlowInvocation(hogFlowEvery),+ ])+ expect(first.notMasked).toHaveLength(1)++ await first.release()++ // The replay is allowed again — an under-release (only part of the batch's+ // increment undone) or a no-op release would leave it masked.+ const replay = await masker.filterByMasking([createExampleHogFlowInvocation(hogFlowEvery)])+ expect(replay.notMasked).toHaveLength(1)++ // Only the released claims came back — an over-release (counter pushed+ // negative) would let this one through too.+ const extra = await masker.filterByMasking([createExampleHogFlowInvocation(hogFlowEvery)])+ expect(extra.masked).toHaveLength(1)+ })+it('resets after ttl for hog flow trigger masking', async () => {const inv = createExampleHogFlowInvocation(hogFlowOncePer)expect((await masker.filterByMasking([inv])).notMasked).toHaveLength(1)diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.tsindex 411acec75f54..d57d0b24388f 100644--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts@@ -117,6 +117,13 @@ export class HogMaskerService {): Promise<{masked: T[]notMasked: T[]+ /**+ * Undoes the Redis increments this call made. The claims are written before the+ * caller persists the invocations, so if that persistence fails, the caller must+ * release the claims — otherwise a replay of the same batch sees every invocation+ * as already-masked and silently drops it.+ */+ release: () => Promise<void>}> {const invocationsWithMasker: GenericHogInvocationWithMasker[] = [...invocations]const masks: Record<string, MaskContext> = {}@@ -158,7 +165,7 @@ export class HogMaskerService {}if (Object.keys(masks).length === 0) {- return { masked: [], notMasked: invocations }+ return { masked: [], notMasked: invocations, release: async () => {} }}const buildPipeline = (pipeline: RedisClientPipeline): void => {@@ -170,10 +177,20 @@ export class HogMaskerService {}const maskContexts = Object.values(masks)+ // Track which stores the increments actually landed on, so release() only+ // decrements those — decrementing a store whose increment failed would push+ // its counters negative and over-allow future executions.+ let incrementedRedis: MaskPipelineResult = null+ let incrementedMirror: MaskPipelineResult = nullconst result = await dualRead('hog-masker.filterByMasking',- () => this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline),- () => this.redisMirror.usePipeline({ name: 'masker-mirror', failOpen: true }, buildPipeline),+ async () =>+ (incrementedRedis = await this.redis.usePipeline({ name: 'masker', failOpen: true }, buildPipeline)),+ async () =>+ (incrementedMirror = await this.redisMirror.usePipeline(+ { name: 'masker-mirror', failOpen: true },+ buildPipeline+ )),(primary, secondary) =>maskContexts.every((masker, index) =>@@ -182,6 +199,25 @@ export class HogMaskerService {))+ const release = async (): Promise<void> => {+ const buildReleasePipeline = (pipeline: RedisClientPipeline): void => {+ maskContexts.forEach(({ hogFunctionId, hash, increment }) => {+ pipeline.incrby(`${REDIS_KEY_TOKENS}/${hogFunctionId}/${hash}`, -increment)+ })+ }+ await Promise.all([+ incrementedRedis+ ? this.redis.usePipeline({ name: 'masker-release', failOpen: true }, buildReleasePipeline)+ : null,+ incrementedMirror+ ? this.redisMirror.usePipeline(+ { name: 'masker-release-mirror', failOpen: true },+ buildReleasePipeline+ )+ : null,+ ])+ }+maskContexts.forEach((masker, index) => {const allowedExecutions = allowedExecutionsForResult(result, index, masker)if (allowedExecutions === null) {@@ -205,9 +241,10 @@ export class HogMaskerService {}return acc},- { masked: [], notMasked: [] } as {+ { masked: [], notMasked: [], release } as {masked: T[]notMasked: T[]+ release: () => Promise<void>})}diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 399726b3cf58..f871fcf89239 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -45,7 +45,7 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, Team } from '../../src/types'import { createRedisV2PoolFromConfig } from '../common/redis/redis-v2'import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'-import { HOG_FILTERS_EXAMPLES } from './_tests/examples'+import { HOG_FILTERS_EXAMPLES, HOG_FLOW_MASK_EXAMPLES } from './_tests/examples'import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from './_tests/fixtures'import { insertHogFlow } from './_tests/fixtures-hogflows'import { CdpApi } from './cdp-api'@@ -57,6 +57,7 @@ import { CdpEventsConsumer } from './consumers/cdp-events.consumer'import { CdpHogflowSubscriptionMatcherConsumer } from './consumers/cdp-hogflow-subscription-matcher.consumer'import { createCdpOutputsRegistry } from './outputs/registry'import {+ CyclotronV2DequeuedJob,CyclotronV2Janitor,CyclotronV2Manager,CyclotronV2Worker,@@ -3711,21 +3712,34 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {// Fresh worker per test — stop() disconnects the underlying Postgres pool,// so a shared instance can't survive past the first test's afterEach.- function buildResolverConsumer(): CdpCyclotronWorkerBatchResolve {+ // `wrapJob` lets a test intercept a dequeued job's methods (e.g. fail a commit once).+ function buildResolverConsumer(+ wrapJob?: (job: CyclotronV2DequeuedJob) => CyclotronV2DequeuedJob+ ): CdpCyclotronWorkerBatchResolve {const cyclotronWorker = new CyclotronV2Worker({pool: { dbUrl: CYCLOTRON_NODE_DB_URL, maxConnections: 10 },queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,pollDelayMs: 100,})+ // The consumer only calls connect/disconnect/isHealthy on the worker.+ const workerForConsumer = wrapJob+ ? ({+ connect: (callback: (jobs: CyclotronV2DequeuedJob[]) => Promise<void>) =>+ cyclotronWorker.connect((jobs) => callback(jobs.map(wrapJob))),+ disconnect: () => cyclotronWorker.disconnect(),+ isHealthy: () => cyclotronWorker.isHealthy(),+ } as unknown as CyclotronV2Worker)+ : cyclotronWorkerconst internalFetchService = new InternalFetchService(hub.INTERNAL_API_BASE_URL, hub.INTERNAL_API_SECRET)const queryService = new HogFlowBatchPersonQueryService(internalFetchService)- return new CdpCyclotronWorkerBatchResolve(hub, deps, cyclotronWorker, queryService, internalFetchService)+ return new CdpCyclotronWorkerBatchResolve(hub, deps, workerForConsumer, queryService, internalFetchService)}- async function insertActiveBatchFlow(): Promise<HogFlow> {+ async function insertActiveBatchFlow(triggerMasking?: HogFlow['trigger_masking']): Promise<HogFlow> {const flow = new FixtureHogFlowBuilder().withTeamId(team.id).withStatus('active')+ .withTriggerMasking(triggerMasking).withWorkflow({actions: {trigger: {@@ -3903,6 +3917,171 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {expect(children.rows).toHaveLength(personIds.length)})+ // Regression test: batch-resolved invocations used to skip trigger_masking entirely+ // (only the event-triggered pipeline applied it), so a scheduled batch workflow with+ // a masking TTL re-enrolled the same audience on every run.+ it('trigger_masking suppresses re-enrolling the same person across two batch runs', async () => {+ const flow = await insertActiveBatchFlow(HOG_FLOW_MASK_EXAMPLES.oncePerTimePeriod.trigger_masking)+ const personId = new UUIDT().toString()+ const statusPuts: Array<{ status: string }> = []++ mockInternalFetch.mockImplementation((url: string, opts: any) => {+ if (url.includes('/user_blast_radius_persons')) {+ return Promise.resolve({+ status: 200,+ headers: {},+ json: () => Promise.resolve({}),+ text: () =>+ Promise.resolve(JSON.stringify({ users_affected: [personId], cursor: null, has_more: false })),+ dump: () => Promise.resolve(),+ })+ }+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {+ statusPuts.push(parseJSON(opts.body) as { status: string })+ return Promise.resolve({+ status: 200,+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('{}'),+ dump: () => Promise.resolve(),+ })+ }+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))+ })++ resolverWorker = buildResolverConsumer()+ await resolverWorker.start()++ // First run: the person hasn't been masked yet, so they get enrolled.+ const firstRunId = new UUIDT().toString()+ await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${firstRunId}`)+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })+ .expect(200)++ await waitForExpect(() => {+ expect(statusPuts).toHaveLength(1)+ }, 20000)++ const firstRunChildren = await cyclotronPool.query(+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,+ [firstRunId]+ )+ expect(firstRunChildren.rows).toHaveLength(1)++ // Second run (simulating the next scheduled re-enrollment): the same person is+ // masked, so no child invocation should be enqueued this time.+ const secondRunId = new UUIDT().toString()+ await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${secondRunId}`)+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })+ .expect(200)++ await waitForExpect(() => {+ expect(statusPuts).toHaveLength(2)+ }, 20000)++ const secondRunChildren = await cyclotronPool.query(+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,+ [secondRunId]+ )+ expect(secondRunChildren.rows).toHaveLength(0)+ })++ // The mask claims land in Redis before the page commits to Postgres. If the commit+ // fails without releasing them, the stall-recovery replay of the same cursor sees+ // the whole page as already-masked and silently drops every enrollment in it.+ it('failed page commit releases mask claims, so the stall-recovery replay still enrolls', async () => {+ const flow = await insertActiveBatchFlow(HOG_FLOW_MASK_EXAMPLES.oncePerTimePeriod.trigger_masking)+ const personId = new UUIDT().toString()+ const statusPuts: Array<{ status: string }> = []++ mockInternalFetch.mockImplementation((url: string, opts: any) => {+ if (url.includes('/user_blast_radius_persons')) {+ return Promise.resolve({+ status: 200,+ headers: {},+ json: () => Promise.resolve({}),+ text: () =>+ Promise.resolve(JSON.stringify({ users_affected: [personId], cursor: null, has_more: false })),+ dump: () => Promise.resolve(),+ })+ }+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {+ statusPuts.push(parseJSON(opts.body) as { status: string })+ return Promise.resolve({+ status: 200,+ headers: {},+ json: () => Promise.resolve({}),+ text: () => Promise.resolve('{}'),+ dump: () => Promise.resolve(),+ })+ }+ return Promise.reject(new Error(`Unexpected internalFetch call to ${url}`))+ })++ let commitFailuresLeft = 1+ resolverWorker = buildResolverConsumer((job) => ({+ ...job,+ bulkCreateAndCheckIn: (input) => {+ if (commitFailuresLeft > 0) {+ commitFailuresLeft--+ return Promise.reject(new Error('injected commit failure'))+ }+ return job.bulkCreateAndCheckIn(input)+ },+ }))+ await resolverWorker.start()++ const parentRunId = new UUIDT().toString()+ await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/${flow.id}/batch_invocations/${parentRunId}`)+ .send({ filters: { filter_test_accounts: false }, max_audience_size: 1000 })+ .expect(200)++ // The first attempt claims the person's mask slot, then hits the injected commit+ // failure. Wait until the resolver has released the claim (counter back to 0) —+ // only then is the job's parked state the same as a real stall.+ const maskRedis = createRedisV2PoolFromConfig({+ connection: hub.CDP_REDIS_HOST+ ? {+ url: hub.CDP_REDIS_HOST,+ options: { port: hub.CDP_REDIS_PORT, password: hub.CDP_REDIS_PASSWORD },+ }+ : { url: hub.REDIS_URL },+ poolMinSize: hub.REDIS_POOL_MIN_SIZE,+ poolMaxSize: hub.REDIS_POOL_MAX_SIZE,+ })+ await waitForExpect(async () => {+ expect(commitFailuresLeft).toBe(0)+ const maskCounters = await maskRedis.useClient({ name: 'mask-peek' }, async (client) => {+ const keys = await client.keys(`@posthog-test/hog-masker/mask/${flow.id}/*`)+ return Promise.all(keys.map((key) => client.get(key)))+ })+ expect(maskCounters).toEqual(['0'])+ }, 20000)++ // What the janitor's stall recovery does to the parked job, without waiting+ // out the stall timeout.+ await cyclotronPool.query(+ `UPDATE cyclotron_jobs SET status = 'available', lock_id = NULL, last_heartbeat = NULL+ WHERE queue_name = $1 AND parent_run_id = $2`,+ [HOGFLOW_BATCH_RESOLVE_QUEUE, parentRunId]+ )++ await waitForExpect(() => {+ expect(statusPuts).toEqual([{ status: 'completed' }])+ }, 20000)++ // The replay re-evaluated masking against the released claim and enrolled the+ // person — without the release it would classify them as masked and enqueue nothing.+ const children = await cyclotronPool.query(+ `SELECT id FROM cyclotron_jobs WHERE queue_name = 'hogflow' AND parent_run_id = $1`,+ [parentRunId]+ )+ expect(children.rows).toHaveLength(1)+ })+it('failed lifecycle: workflow deleted before processing → resolver transitions to failed → Django PUT status=failed', async () => {const flow = await insertActiveBatchFlow()const parentRunId = new UUIDT().toString()