: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): handle batch hog flow audience-query failures gracefully (#58146)
Ben Whitea3e40f87f841
diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.tsindex 4dd448f74798..073ea130c53b 100644--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.test.ts@@ -489,6 +489,122 @@ describe('CdpBatchHogFlowRequestsConsumer', () => {customVar3: null,})})++ it('should record a workflow failure and not throw when audience query rejects', async () => {+ const hogFlow = await insertHogFlow(+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withSimpleWorkflow({+ trigger: {+ type: 'batch',+ filters: { properties: [] },+ },+ })+ .build()+ )++ const queueAppMetricSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueAppMetric')+ const queueLogsSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueLogs')++ // Simulate the Django endpoint failing (e.g. unsupported flag-typed property).+ processor['hogFlowBatchPersonQueryService'].getBlastRadiusPersons = jest+ .fn()+ .mockRejectedValue(new Error('Failed to fetch blast radius persons: 500 Internal server error'))++ const batchRequest: BatchHogFlowRequest = {+ teamId: team.id,+ hogFlowId: hogFlow.id,+ parentRunId: new UUIDT().toString(),+ filters: {+ properties: [{ key: 'flag-key', value: ['true'], operator: 'exact', type: 'flag' as any }],+ },+ }++ // Must resolve, not reject — the consumer should swallow the failure and continue.+ const result = await processor['createHogFlowInvocations']({+ batchHogFlowRequest: batchRequest,+ team,+ hogFlow,+ })++ expect(result).toHaveLength(0)++ expect(queueAppMetricSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ team_id: hogFlow.team_id,+ app_source_id: hogFlow.id,+ instance_id: batchRequest.parentRunId,+ metric_kind: 'failure',+ metric_name: 'trigger_failed',+ count: 1,+ }),+ 'hog_flow'+ )++ expect(queueLogsSpy).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ team_id: hogFlow.team_id,+ log_source: 'hog_flow',+ log_source_id: batchRequest.parentRunId,+ instance_id: batchRequest.parentRunId,+ level: 'error',+ message: expect.stringContaining('Failed to resolve batch audience'),+ }),+ ],+ 'hog_flow'+ )+ })++ it('should record a missing_filters failure when filters.properties is empty', async () => {+ const hogFlow = await insertHogFlow(+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withSimpleWorkflow({+ trigger: {+ type: 'batch',+ filters: {} as any,+ },+ })+ .build()+ )++ const queueAppMetricSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueAppMetric')+ const queueLogsSpy = jest.spyOn(processor.hogFunctionMonitoringService, 'queueLogs')++ const batchRequest: BatchHogFlowRequest = {+ teamId: team.id,+ hogFlowId: hogFlow.id,+ parentRunId: new UUIDT().toString(),+ filters: {},+ }++ const result = await processor['createHogFlowInvocations']({+ batchHogFlowRequest: batchRequest,+ team,+ hogFlow,+ })++ expect(result).toHaveLength(0)+ expect(queueAppMetricSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ metric_kind: 'failure',+ metric_name: 'trigger_failed',+ instance_id: batchRequest.parentRunId,+ }),+ 'hog_flow'+ )+ expect(queueLogsSpy).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ log_source_id: batchRequest.parentRunId,+ level: 'error',+ message: expect.stringContaining('no property filters'),+ }),+ ],+ 'hog_flow'+ )+ })})describe('processBatch', () => {diff --git a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.tsindex 94022bbc9416..0746c19dae44 100644--- a/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-batch-hogflow.consumer.ts@@ -9,15 +9,15 @@ import { captureException } from '~/utils/posthog'import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'import { HealthCheckResult, PluginsServerConfig, Team } from '../../types'-import { logger } from '../../utils/logger'+import { logger, serializeError } from '../../utils/logger'import { UUIDT } from '../../utils/utils'import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'import { CyclotronJobQueue } from '../services/job-queue/job-queue'import { CyclotronJobInvocation, HogFunctionFilters } from '../types'-import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals } from '../utils'+import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals, logEntry } from '../utils'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'-import { counterParseError } from './metrics'+import { counterBatchHogFlowTriggerFailed, counterParseError } from './metrics'export interface BatchHogFlowRequest {teamId: number@@ -107,6 +107,11 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServif (!filters.properties || !filters.properties.length) {logger.error('Batch HogFlow request missing property filters', { batchHogFlowRequest })+ this.recordBatchTriggerFailure(+ batchHogFlowRequestMessage,+ 'missing_filters',+ 'Batch trigger has no property filters configured.'+ )return []}@@ -124,58 +129,80 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServlet cursor: string | null = nulllet totalPersonsProcessed = 0- // Fetch persons in batches using cursor-based pagination- do {- const blastRadiusPersons = await instrumentFn(- 'cdpProducer.generateBatch.queueMatchingPersons.getBlastRadiusPersons',- async () => {- return await this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(- team,- filters,- batchHogFlowRequest.group_type_index,- cursor+ try {+ // Fetch persons in batches using cursor-based pagination+ do {+ const blastRadiusPersons = await instrumentFn(+ 'cdpProducer.generateBatch.queueMatchingPersons.getBlastRadiusPersons',+ async () => {+ return await this.hogFlowBatchPersonQueryService.getBlastRadiusPersons(+ team,+ filters,+ batchHogFlowRequest.group_type_index,+ cursor+ )+ }+ )++ const batchPersonsCount = blastRadiusPersons.users_affected.length+ totalPersonsProcessed += batchPersonsCount++ if (totalPersonsProcessed > this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE) {+ logger.warn(+ '⚠️',+ `Batch HogFlow run ${batchHogFlowRequest.parentRunId} has exceeded the maximum audience size of ${this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE}. Stopping further processing.`,+ { totalPersonsProcessed, batchHogFlowRequest })+ break}- )- const batchPersonsCount = blastRadiusPersons.users_affected.length- totalPersonsProcessed += batchPersonsCount-- if (totalPersonsProcessed > this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE) {- logger.warn(- '⚠️',- `Batch HogFlow run ${batchHogFlowRequest.parentRunId} has exceeded the maximum audience size of ${this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE}. Stopping further processing.`,- { totalPersonsProcessed, batchHogFlowRequest }+ logger.info(+ '📝',+ `Fetched ${batchPersonsCount} persons (${totalPersonsProcessed} total) for batch HogFlow run ${batchHogFlowRequest.parentRunId}`)- break- }-- logger.info(- '📝',- `Fetched ${batchPersonsCount} persons (${totalPersonsProcessed} total) for batch HogFlow run ${batchHogFlowRequest.parentRunId}`- )- // Create invocations for this batch of persons- const batchInvocations = blastRadiusPersons.users_affected.map((personId) =>- this.createHogFlowInvocation({- parentRunId: batchHogFlowRequest.parentRunId,- hogFlow,- team,- personId,- defaultVariables,- })- )+ // Create invocations for this batch of persons+ const batchInvocations = blastRadiusPersons.users_affected.map((personId) =>+ this.createHogFlowInvocation({+ parentRunId: batchHogFlowRequest.parentRunId,+ hogFlow,+ team,+ personId,+ defaultVariables,+ })+ )- allInvocations.push(...batchInvocations)+ allInvocations.push(...batchInvocations)- // Update cursor for next iteration- cursor = blastRadiusPersons.cursor+ // Update cursor for next iteration+ cursor = blastRadiusPersons.cursor- // Continue if there are more persons to fetch- if (!blastRadiusPersons.has_more) {- break- }- } while (cursor)+ // Continue if there are more persons to fetch+ if (!blastRadiusPersons.has_more) {+ break+ }+ } while (cursor)+ } catch (error) {+ // Audience resolution failed (e.g. unsupported filter property like a feature flag in person scope).+ // Record a workflow-level failure so the run is observable in logs/metrics, then drop the batch+ // instead of crashing the consumer and re-processing the same poison message in a tight loop.+ const message = error instanceof Error ? error.message : String(error)+ logger.error('🔴', 'Failed to resolve audience for batch HogFlow run, skipping batch', {+ error: serializeError(error),+ hogFlowId: hogFlow.id,+ teamId: team.id,+ parentRunId: batchHogFlowRequest.parentRunId,+ })+ captureException(error, {+ tags: { hogFlowId: hogFlow.id, parentRunId: batchHogFlowRequest.parentRunId },+ })+ this.recordBatchTriggerFailure(+ batchHogFlowRequestMessage,+ 'audience_query_failed',+ `Failed to resolve batch audience: ${message}`+ )+ return []+ }logger.info('✅',@@ -185,6 +212,41 @@ export class CdpBatchHogFlowRequestsConsumer extends CdpConsumerBase<PluginsServreturn allInvocations}+ private recordBatchTriggerFailure(+ batchHogFlowRequestMessage: BatchHogFlowRequestMessage,+ reason: 'missing_filters' | 'audience_query_failed',+ userMessage: string+ ): void {+ const { batchHogFlowRequest, hogFlow } = batchHogFlowRequestMessage++ counterBatchHogFlowTriggerFailed.labels({ hog_flow_id: hogFlow.id, reason }).inc()++ this.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: hogFlow.team_id,+ app_source_id: hogFlow.id,+ instance_id: batchHogFlowRequest.parentRunId,+ metric_kind: 'failure',+ metric_name: 'trigger_failed',+ count: 1,+ },+ 'hog_flow'+ )++ this.hogFunctionMonitoringService.queueLogs(+ [+ {+ team_id: hogFlow.team_id,+ log_source: 'hog_flow',+ log_source_id: batchHogFlowRequest.parentRunId,+ instance_id: batchHogFlowRequest.parentRunId,+ ...logEntry('error', userMessage),+ },+ ],+ 'hog_flow'+ )+ }+private async processBatchHogFlowRequest(batchHogFlowRequests: BatchHogFlowRequestMessage[]): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {diff --git a/nodejs/src/cdp/consumers/metrics.ts b/nodejs/src/cdp/consumers/metrics.tsindex c06285b9c84b..e09cc4f4fe7f 100644--- a/nodejs/src/cdp/consumers/metrics.ts+++ b/nodejs/src/cdp/consumers/metrics.ts@@ -17,3 +17,9 @@ export const counterHogFunctionStateOnEvent = new Counter({help: 'Metric the state of a hog function that matched an event',labelNames: ['state', 'kind'],})++export const counterBatchHogFlowTriggerFailed = new Counter({+ name: 'cdp_batch_hog_flow_trigger_failed',+ help: 'A batch hog flow run failed during audience resolution and was skipped',+ labelNames: ['hog_flow_id', 'reason'],+})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.tsindex a391f2e0a115..56905cf99eb6 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts@@ -1,7 +1,7 @@import { InternalFetchService } from '~/common/services/internal-fetch'import { Team } from '~/types'import { parseJSON } from '~/utils/json-parse'-import { logger } from '~/utils/logger'+import { logger, serializeError } from '~/utils/logger'import { HogFunctionFilters } from '../../types'@@ -48,7 +48,10 @@ export class HogFlowBatchPersonQueryService {})if (!fetchResponse || fetchError) {- logger.error('Error fetching blast radius from Django', { error: fetchError, urlPath })+ logger.error('Error fetching blast radius from Django', {+ error: serializeError(fetchError),+ urlPath,+ })throw fetchError}@@ -66,7 +69,7 @@ export class HogFlowBatchPersonQueryService {return data} catch (error) {- logger.error('Error calling blast radius endpoint', { error, urlPath })+ logger.error('Error calling blast radius endpoint', { error: serializeError(error), urlPath })throw error}}@@ -99,7 +102,10 @@ export class HogFlowBatchPersonQueryService {})if (!fetchResponse || fetchError) {- logger.error('Error fetching blast radius persons from Django', { error: fetchError, urlPath })+ logger.error('Error fetching blast radius persons from Django', {+ error: serializeError(fetchError),+ urlPath,+ })throw fetchError}@@ -117,7 +123,7 @@ export class HogFlowBatchPersonQueryService {return data} catch (error) {- logger.error('Error calling blast radius persons endpoint', { error, urlPath })+ logger.error('Error calling blast radius persons endpoint', { error: serializeError(error), urlPath })throw error}}diff --git a/nodejs/src/utils/logger.ts b/nodejs/src/utils/logger.tsindex 65336e2f6b2b..0f7d6715ee32 100644--- a/nodejs/src/utils/logger.ts+++ b/nodejs/src/utils/logger.ts@@ -113,7 +113,7 @@ export const logger = new Logger(defaultConfig.PLUGIN_SERVER_MODE ?? 'MAIN')export function serializeError(error: unknown): Record<string, unknown> | unknown {if (error instanceof Error) {- return { name: error.name, message: error.message }+ return { name: error.name, message: error.message, stack: error.stack }}return error}