: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): record batch runs as started so parked runs are visible (#81477)
Kyle Swank64e28735a776
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 ada63ebac8e8..e3979c8e8fc4 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,67 +1,234 @@import { HogFlow } from '~/cdp/schema/hogflow'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { parseJSON } from '~/common/utils/json-parse'import { Team } from '~/types'import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { HOG_FLOW_MASK_EXAMPLES } from '../_tests/examples'+import { CdpOutput } from '../cdp-services'+import { BatchResolverState } from '../services/hogflows/batch-resolver.types'+import {+ HogInvocationResultRow,+ HogInvocationResultsService,+} from '../services/monitoring/hog-invocation-results.service'import { CyclotronJobInvocationHogFlow } from '../types'-import { buildAccountHogFlowInvocation } from './cdp-cyclotron-worker-batch-resolve.consumer'+import {+ CdpCyclotronWorkerBatchResolve,+ buildAccountHogFlowInvocation,+} from './cdp-cyclotron-worker-batch-resolve.consumer'-describe('buildAccountHogFlowInvocation', () => {+describe('CdpCyclotronWorkerBatchResolve', () => {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,- hogFlow,- externalId: 'acme-1',- groupType: 'customer',- defaultVariables: { greeting: 'hi' },+ describe('buildAccountHogFlowInvocation', () => {+ it('carries the account group key and no person', () => {+ const invocation = buildAccountHogFlowInvocation({+ siteUrl: 'https://us.posthog.com',+ parentRunId: 'batch-job-1',+ team,+ hogFlow,+ externalId: 'acme-1',+ groupType: 'customer',+ defaultVariables: { greeting: 'hi' },+ })++ const state = invocation.state as CyclotronJobInvocationHogFlow['state']++ expect(state.event.event).toEqual('$batch_hog_flow_invocation')+ // distinct_id doubles as the per-account key for invocation_results; it must NOT+ // resolve to a person (the hogflow worker skips the lookup for account audiences).+ expect(state.event.distinct_id).toEqual('acme-1')+ expect(state.event.properties['$groups']).toEqual({ customer: 'acme-1' })+ expect(state.personId).toBeUndefined()+ // The stamp is what the hogflow worker trusts when the live trigger has been+ // edited to a person audience while these children were still queued.+ expect(state.accountAudience).toBe(true)+ // Account broadcasts convert long after the send, so the run has to carry the version+ // that sent or the conversion is credited to whatever is published by then.+ expect(state.flowVersion).toBe(4)+ expect(state.variables).toEqual({ greeting: 'hi' })+ expect(invocation.parentRunId).toEqual('batch-job-1')+ expect(invocation.queue).toEqual('hogflow')+ expect((invocation as any).person).toBeUndefined()})- const state = invocation.state as CyclotronJobInvocationHogFlow['state']-- expect(state.event.event).toEqual('$batch_hog_flow_invocation')- // distinct_id doubles as the per-account key for invocation_results; it must NOT- // resolve to a person (the hogflow worker skips the lookup for account audiences).- expect(state.event.distinct_id).toEqual('acme-1')- expect(state.event.properties['$groups']).toEqual({ customer: 'acme-1' })- expect(state.personId).toBeUndefined()- // The stamp is what the hogflow worker trusts when the live trigger has been- // edited to a person audience while these children were still queued.- expect(state.accountAudience).toBe(true)- // Account broadcasts convert long after the send, so the run has to carry the version- // that sent or the conversion is credited to whatever is published by then.- expect(state.flowVersion).toBe(4)- expect(state.variables).toEqual({ greeting: 'hi' })- expect(invocation.parentRunId).toEqual('batch-job-1')- expect(invocation.queue).toEqual('hogflow')- expect((invocation as any).person).toBeUndefined()+ // Two things key off this object. HogMaskerService.filterByMasking() only recognizes an+ // invocation as a hog flow invocation (and applies trigger_masking) when it carries a+ // `hogFlow`, and the invocation-results service classifies rows by the same shape — so a+ // regression here silently stops masking batch runs and drops their rows out of the+ // workflow invocations list, which filters on hog_flow.+ 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)+ })})- // 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: {},+ describe('processOnePage run-level monitoring', () => {+ const BATCH_JOB_ID = 'batch-job-1'++ let consumer: CdpCyclotronWorkerBatchResolve+ let queueAppMetrics: jest.Mock+ let outputs: jest.Mocked<IngestionOutputs<CdpOutput>>+ let rowsService: HogInvocationResultsService+ let bulkCreateAndCheckIn: jest.Mock+ let filterByMasking: jest.Mock+ let release: jest.Mock++ const state: BatchResolverState = {+ batchJobId: BATCH_JOB_ID,+ teamId: team.id,+ hogFlowId: hogFlow.id,+ cursor: null,+ filters: { properties: [] },+ maxAudienceSize: 100,+ totalEnqueued: 0,+ pagesProcessed: 0,+ attempts: 0,+ variables: {},+ startedAt: '2026-08-11T00:00:00.000Z',+ }++ const processPage = async (): Promise<void> =>+ await (consumer as any).processOnePage({ bulkCreateAndCheckIn, reschedule: jest.fn() }, state)++ // The rows the real service produced on flush. Asserting on these rather than on mock+ // call args is what catches a misclassification: function_kind is derived structurally+ // inside the service ('hogFlow' in invocation), which a mocked service never evaluates.+ const producedRows = (): HogInvocationResultRow[] =>+ outputs.produce.mock.calls.map(+ ([, message]) => parseJSON(message.value!.toString('utf8')) as HogInvocationResultRow+ )++ const triggeredMetrics = (): any[] =>+ queueAppMetrics.mock.calls.flatMap(([metrics]) => metrics).filter((m) => m.metric_name === 'triggered')++ beforeEach(() => {+ queueAppMetrics = jest.fn()+ bulkCreateAndCheckIn = jest.fn().mockResolvedValue(undefined)+ release = jest.fn().mockResolvedValue(undefined)+ // Masking itself is covered by hog-masker.service.test.ts; stubbing the partition+ // here is what lets each case fix which runs are masked and assert how the consumer+ // routes them.+ filterByMasking = jest.fn((invocations) => ({ masked: [], notMasked: invocations, release }))+ outputs = {+ produce: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<IngestionOutputs<CdpOutput>>+ rowsService = new HogInvocationResultsService(outputs, { HOG_INVOCATION_RESULTS_ENABLED: true })++ // The base constructor builds redis/valkey-backed services, so assemble the+ // instance directly — this exercises processOnePage without any live boundary.+ // The rows service is real (only its produce boundary is mocked) because the+ // regressions to catch live inside it: how it classifies and stamps the+ // invocations this consumer builds.+ consumer = Object.create(CdpCyclotronWorkerBatchResolve.prototype)+ Object.assign(consumer, {+ config: { SITE_URL: 'https://us.posthog.com' },+ deps: { teamManager: { getTeam: jest.fn().mockResolvedValue(team) } },+ hogFlowManager: { getHogFlow: jest.fn().mockResolvedValue(hogFlow) },+ hogFlowBatchPersonQueryService: {+ getBlastRadiusPersons: jest.fn().mockResolvedValue({+ users_affected: ['person-1', 'person-2'],+ cursor: null,+ has_more: false,+ }),+ },+ hogMasker: { filterByMasking },+ hogFunctionMonitoringService: { queueAppMetrics, queueLogs: jest.fn() },+ invocationResultsService: { invocationResultsRowsService: rowsService },+ })+ })++ it('counts each enrolled person as a triggered run against the batch job', async () => {+ await processPage()++ const metrics = triggeredMetrics()+ expect(metrics).toHaveLength(2)+ for (const metric of metrics) {+ // Keyed on the batch job, not the workflow — that is where the batch metrics+ // view looks, and the workflow id would silently read as zero runs started.+ expect(metric.app_source_id).toEqual(BATCH_JOB_ID)+ expect(metric.team_id).toEqual(team.id)+ expect(metric.metric_kind).toEqual('other')+ expect(metric.count).toEqual(1)+ // Run-level metrics carry no instance id; a step id here would hide them from the+ // started/in-progress counters, which filter on the empty instance.+ expect(metric.instance_id).toBeUndefined()+ }+ })++ it('records each enrolled person as a running hog_flow invocation so parked runs are listable', async () => {+ await processPage()+ await rowsService.flush()++ const rows = producedRows()+ expect(rows).toHaveLength(2)+ for (const row of rows) {+ // hog_flow, not hog_function: the workflow invocations API only reads rows with+ // this kind, so a misclassified row is invisible even though it was written.+ expect(row.function_kind).toEqual('hog_flow')+ expect(row.function_id).toEqual(hogFlow.id)+ expect(row.parent_run_id).toEqual(BATCH_JOB_ID)+ expect(row.status).toEqual('running')+ }+ })++ it('stamps the enqueue time into the state that gets persisted', async () => {+ // The stamp is written onto the invocation by queueLifecycleRow, so it only lands in+ // cyclotron if that runs before the state is serialized. Out of order, the terminal+ // row written when the run wakes records the wake time and wins the argMax collapse.+ await processPage()++ const { newJobs } = bulkCreateAndCheckIn.mock.calls[0][0]+ expect(newJobs).toHaveLength(2)+ for (const job of newJobs) {+ expect(job.state.toString()).toContain('firstScheduledAt')+ }})- expect(invocation.hogFlow).toBe(maskedHogFlow)- expect(invocation.hogFlow.trigger_masking).toEqual(HOG_FLOW_MASK_EXAMPLES.everyTime.trigger_masking)+ it('leaves masked runs out of both the triggered count and the invocations list', async () => {+ // A masked run is never enqueued, so counting it as started would strand it in the+ // in-progress figure forever, and its running row would never get a terminal row.+ filterByMasking.mockImplementation((invocations: CyclotronJobInvocationHogFlow[]) => ({+ masked: [invocations[0]],+ notMasked: [invocations[1]],+ release,+ }))++ await processPage()+ await rowsService.flush()++ expect(triggeredMetrics()).toHaveLength(1)+ expect(producedRows()).toHaveLength(1)+ })++ it('drops the queued rows and releases the mask claims when the page fails to commit', async () => {+ // The commit is atomic with the cursor advance, so a failure replays the whole page.+ // Rows left queued here would be written twice.+ bulkCreateAndCheckIn.mockRejectedValue(new Error('postgres is down'))++ await expect(processPage()).rejects.toThrow('postgres is down')+ await rowsService.flush()++ expect(producedRows()).toHaveLength(0)+ expect(release).toHaveBeenCalledTimes(1)+ expect(triggeredMetrics()).toHaveLength(0)+ })})})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 53fed980a58d..4264cfdb0dfe 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@@ -162,7 +162,10 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe// transitionToFailedTerminal) would otherwise wait for a later terminal// dequeue — under multi-replica that's a different worker, and under a// restart it's gone entirely.- await this.hogFunctionMonitoringService.flush().catch((err) => {+ await Promise.all([+ this.hogFunctionMonitoringService.flush(),+ this.invocationResultsService.invocationResultsRowsService.flush(),+ ]).catch((err) => {logger.warn('⚠️', `${this.name} - failed to flush monitoring after resolver dequeue`, {error: serializeError(err),})@@ -290,6 +293,17 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe// with a masking TTL re-enrolls the same audience on every scheduled run.const { masked, notMasked, release } = await this.hogMasker.filterByMasking(builtInvocations)+ // Only the unmasked runs get a lifecycle row: a masked one is never enqueued, so a+ // `running` row for it would sit in the invocations list forever with no terminal row.+ //+ // Queued before serializing, because queueLifecycleRow stamps `state.firstScheduledAt`+ // on the invocation and the terminal row written after the run wakes has to inherit it —+ // otherwise that row records the wake time and wins the ReplacingMergeTree collapse,+ // mislabeling when the run started.+ for (const invocation of notMasked) {+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }+const children: CyclotronV2JobInit[] = notMasked.map((invocation) => invocationToV2JobInit(invocation))const newState: BatchResolverState = {@@ -317,6 +331,11 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe// 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()+ // Same reasoning for the lifecycle rows queued above: the replay re-queues them,+ // so leaving these would write each run's `running` row twice.+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor(+ notMasked.map((invocation) => invocation.id)+ )throw err}@@ -336,6 +355,24 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe)}+ // Mirrors the `triggered` metric the realtime trigger path emits per invocation, so+ // batch runs count towards "workflows started" (and the derived in-progress count).+ // Masked runs are excluded: counting one as started would leave it in progress forever,+ // since it never runs and so never records a terminal `succeeded`.+ // Keyed on the batch job id like every other metric a batch run emits; `instance_id`+ // is left unset because this is a run-level, not a step-level, metric.+ this.hogFunctionMonitoringService.queueAppMetrics(+ notMasked.map((invocation) => ({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? hogFlow.id,+ metric_kind: 'other' as const,+ metric_name: 'triggered' as const,+ count: 1,+ app_source_version: { id: hogFlow.id, version: hogFlow.version },+ })),+ 'hog_flow'+ )+if (pageTruncated) {this.emitTruncationLog(newState)}@@ -525,16 +562,20 @@ export function buildAccountHogFlowInvocation(params: {// 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.hogFlow.version,- } as any,+ },teamId: params.team.id,functionId: params.hogFlow.id,+ // In-memory only (persistence serializes just `state`), but load-bearing for+ // monitoring: the invocation-results service classifies by shape (`'hogFlow' in+ // invocation`), and a row not classified as hog_flow never shows up in the+ // workflow invocations list.hogFlow: params.hogFlow,parentRunId: params.parentRunId,filterGlobals,queue: 'hogflow' as const,queuePriority: 1,queueScheduledAt: DateTime.now(),- } as CyclotronJobInvocationHogFlow+ }}// Mirrors `createHogFlowInvocation` from the legacy Kafka consumer so children@@ -565,15 +606,17 @@ function buildHogFlowInvocation(params: {// 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.hogFlow.version,- } as any,+ },teamId: params.team.id,functionId: params.hogFlow.id,+ // See buildAccountHogFlowInvocation: in-memory only, but drives the shape-based+ // hog_flow classification of the `running` lifecycle rows.hogFlow: params.hogFlow,parentRunId: params.parentRunId,- person: invocationGlobals.person as any,+ person: invocationGlobals.person,filterGlobals,queue: 'hogflow' as const,queuePriority: 1,queueScheduledAt: DateTime.now(),- } as CyclotronJobInvocationHogFlow+ }}diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex f871fcf89239..d5746dd9c33d 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -3660,6 +3660,8 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {let api: CdpApilet batchResolverProducer: CyclotronV2Managerlet deps: ReturnType<typeof createCdpConsumerDeps>+ let kafkaProducer: KafkaProducerWrapper+ let mockProducerObserver: KafkaProducerObserver// Fresh consumer per test — built in the it() body, stopped in afterEach.let resolverWorker: CdpCyclotronWorkerBatchResolve | undefined@@ -3667,14 +3669,21 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {cyclotronPool = new Pool({ connectionString: CYCLOTRON_NODE_DB_URL })MockKafkaProducerWrapper.create = jest.fn((...args) => ActualKafkaProducerWrapper.create(...args))- await ensureKafkaTopics(TEST_KAFKA_TOPICS)+ // KAFKA_HOG_INVOCATION_RESULTS isn't in TEST_KAFKA_TOPICS — the resolver produces a+ // running row per enrolled person there, so the topic has to exist or the produce fails.+ await ensureKafkaTopics([...TEST_KAFKA_TOPICS, KAFKA_HOG_INVOCATION_RESULTS])hub = await createHub({SITE_URL: 'http://localhost:8000',})+ // Lifecycle rows are gated on this flag, which is off by default outside dev — without+ // it the row assertions below would pass against an empty topic.+ hub.HOG_INVOCATION_RESULTS_ENABLED = trueconst { createMockJobQueue } = require('../../tests/helpers/mocks/job-queue.mock')- deps = createCdpConsumerDeps(hub)+ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ mockProducerObserver = new KafkaProducerObserver(kafkaProducer)+ deps = createCdpConsumerDeps(hub, kafkaProducer)batchResolverProducer = new CyclotronV2Manager({pool: { dbUrl: CYCLOTRON_NODE_DB_URL, maxConnections: 5 },})@@ -3692,6 +3701,7 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {afterAll(async () => {server?.close()await batchResolverProducer?.disconnect()+ await kafkaProducer?.disconnect()await closeHub(hub)await cyclotronPool.end()})@@ -3701,6 +3711,7 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {await cyclotronPool.query(`DELETE FROM cyclotron_jobs`)team = await getFirstTeam(hub.postgres)resolverWorker = undefined+ mockProducerObserver.resetKafkaProducer()})afterEach(async () => {@@ -3915,6 +3926,40 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {[parentRunId])expect(children.rows).toHaveLength(personIds.length)++ // Enrolling a person has to register as a started run at the same time as it enqueues+ // the work. Both of these used to be skipped here (only the event-triggered path wrote+ // them), which read on the workflow page as a batch that never started and had no runs+ // to list — for the whole of any delay the flow was parked on.+ await waitForExpect(() => {+ const triggered = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ .filter((m: any) => m.value.app_source === 'hog_flow' && m.value.metric_name === 'triggered')+ // Summed, not counted: the aggregator collapses a flush window's metrics onto one+ // message per key, so a 3-page resolve produces fewer messages than persons.+ expect(triggered.reduce((total, m: any) => total + m.value.count, 0)).toBe(personIds.length)+ for (const metric of triggered) {+ // Keyed on the batch run, which is what the batch metrics view queries. Keyed on+ // the workflow id instead, the count is real but the page still reads zero.+ expect((metric as any).value.app_source_id).toBe(parentRunId)+ // Run-level, so no step id — the started and in-progress counters filter on the+ // empty instance and would skip these otherwise.+ expect((metric as any).value.instance_id).toBe('')+ }++ const rows = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_HOG_INVOCATION_RESULTS)+ .map((m: any) => m.value)+ expect(rows).toHaveLength(personIds.length)+ for (const row of rows) {+ // hog_flow, not hog_function: the invocations API filters on this, so a+ // misclassified row is written but never listed.+ expect(row.function_kind).toBe('hog_flow')+ expect(row.function_id).toBe(flow.id)+ expect(row.parent_run_id).toBe(parentRunId)+ expect(row.status).toBe('running')+ }+ }, 10000)})// Regression test: batch-resolved invocations used to skip trigger_masking entirely