: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(cdp): name the timeout when a batch audience fetch aborts (#101949)
Meikel Ratzcd20d0e740ef
diff --git a/docs/internal/workflows-batch-audience-resolution.md b/docs/internal/workflows-batch-audience-resolution.mdindex 56838e5dcf62..30ddead9c4ae 100644--- a/docs/internal/workflows-batch-audience-resolution.md+++ b/docs/internal/workflows-batch-audience-resolution.md@@ -12,7 +12,10 @@ The page fetch runs a ClickHouse query, so it does not fit the generic 3s `EXTER- `CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS` (default `30000`) — client-side budget in milliseconds for each audience fetch (blast-radius count, persons page, account page).-A fetch that exceeds the budget aborts, retries up to `MAX_RESOLVER_ATTEMPTS` times with backoff, and then the run is marked failed with `Batch resolver failed: Audience fetch failed permanently…` on the workflow's log stream. Keep the budget under the HogQL default `max_execution_time` (60s): above it, the client only waits longer for a query ClickHouse will kill anyway. Note the client abort does not cancel the ClickHouse query — a query slower than the budget keeps running server-side until the HogQL cap, so a too-small budget wastes a full query execution per attempt.+A fetch that exceeds the budget aborts, retries up to `MAX_RESOLVER_ATTEMPTS` times with backoff, and then the run is marked failed on the workflow's log stream.+A timeout gets its own terminal reason, `Batch resolver failed: Audience query timed out…`, which names the budget and the attempt count.+Any other fetch failure keeps the generic `Batch resolver failed: Audience fetch failed permanently…`, so search for both texts when you triage a failed run.+Keep the budget under the HogQL default `max_execution_time` (60s): above it, the client only waits longer for a query ClickHouse will kill anyway. Note the client abort does not cancel the ClickHouse query — a query slower than the budget keeps running server-side until the HogQL cap, so a too-small budget wastes a full query execution per attempt.## Lock heartbeats and batch size@@ -29,7 +32,8 @@ This keeps an allowed slow fetch from reporting the worker as unhealthy while it## Observing-- Fetch durations: `instrumented_function_duration_seconds` for `cdpBatchResolve.getBlastRadiusPersons` and `cdpBatchResolve.getAccountAudiencePage`. Watch the p99 against the budget before tuning either.+- Fetch durations: `instrumented_function_duration_seconds` for `cdpBatchResolve.getBlastRadiusPersons` and `cdpBatchResolve.getAccountAudiencePage`. Read the bucket counts rather than a quantile before tuning either. The finite bucket edges are 0.025, 0.1, 0.4, 1.6, 6.4, 25.6 and 102.4 seconds, so a quantile between two edges reports the share of slow fetches and not how long they took. `CdpBatchAudienceFetchSlow` counts fetches slower than 25.6s, the edge closest to the budget, and fires before any fetch aborts. That alert reads the persons function only. A slow account page therefore gets no warning before it starts to time out, so watch its bucket counts by hand or widen the alert.+- Timeouts: `cdp_batch_hog_flow_audience_fetch_timeout{endpoint}` counts each fetch that used its full budget and aborted. A timeout raises `AudienceFetchTimeoutError`, which is a separate type from a transport failure, so the retry logs and the customer-visible failure reason name the timeout. `CdpBatchAudienceFetchTimingOut` alerts on a sustained rate. Both alerts live in [PostHog/charts `alerts/specs/cdp.yaml`](https://github.com/PostHog/charts/blob/main/alerts/specs/cdp.yaml).- Failures: `cdp_batch_hog_flow_resolver_pages_processed{outcome="fetch_failure"}`, and a `Batch resolver failed: <reason>` row in ClickHouse `log_entries` with `log_source = 'hog_flow'` and `log_source_id` = the **batch job id** (not the workflow id).## Known gap: the failure reason is not visible in the appdiff --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 65af0b24c271..ec4e9be5c481 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@@ -8,7 +8,12 @@ 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, serializeResolverState } from '../services/hogflows/batch-resolver.types'+import {+ BatchResolverState,+ MAX_RESOLVER_ATTEMPTS,+ serializeResolverState,+} from '../services/hogflows/batch-resolver.types'+import { AudienceFetchTimeoutError } from '../services/hogflows/hogflow-batch-person-query.service'import {HogInvocationResultRow,HogInvocationResultsService,@@ -377,4 +382,92 @@ describe('CdpCyclotronWorkerBatchResolve', () => {expect(heartbeat).toHaveBeenCalledTimes(2)})})+ describe('permanent audience fetch failure', () => {+ const buildConsumer = (getBlastRadiusPersons: jest.Mock, queueLogs: jest.Mock): any => {+ const 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 },+ hogFunctionMonitoringService: {+ queueAppMetrics: jest.fn(),+ queueLogs,+ flush: jest.fn().mockResolvedValue(undefined),+ },+ invocationResultsService: {+ invocationResultsRowsService: { flush: jest.fn().mockResolvedValue(undefined) },+ },+ })+ return consumer+ }++ const buildJob = (state: BatchResolverState): any => ({+ id: 'job-last-attempt',+ teamId: team.id,+ functionId: hogFlow.id,+ parentRunId: state.batchJobId,+ cancelRequestedAt: null,+ state: serializeResolverState(state),+ heartbeat: jest.fn().mockResolvedValue(undefined),+ bulkCreateAndCheckIn: jest.fn().mockResolvedValue({ newJobIds: [] }),+ reschedule: jest.fn().mockResolvedValue(undefined),+ ack: jest.fn().mockResolvedValue(undefined),+ fail: jest.fn().mockResolvedValue(undefined),+ })++ // One attempt short of the cap, so the failure in each case is the permanent one.+ const lastAttemptState = (): BatchResolverState => ({+ batchJobId: 'batch-job-fail',+ teamId: team.id,+ hogFlowId: hogFlow.id,+ cursor: null,+ filters: { properties: [] },+ maxAudienceSize: 100,+ totalEnqueued: 0,+ pagesProcessed: 0,+ attempts: MAX_RESOLVER_ATTEMPTS - 1,+ variables: {},+ startedAt: '2026-08-11T00:00:00.000Z',+ })++ it('tells the customer what to change when the audience query timed out', async () => {+ const queueLogs = jest.fn()+ const consumer = buildConsumer(+ jest.fn().mockRejectedValue(new AudienceFetchTimeoutError('user_blast_radius_persons', 30_000)),+ queueLogs+ )+ const job = buildJob(lastAttemptState())++ await consumer.processResolverJob(job)++ expect(queueLogs).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ message:+ 'Batch resolver failed: Audience query timed out after 30s on the last of ' ++ `${MAX_RESOLVER_ATTEMPTS} attempts. Use fewer or simpler audience filters, or a smaller audience.`,+ }),+ ],+ 'hog_flow'+ )+ })++ it('keeps the generic reason for a failure that is not a timeout', async () => {+ const queueLogs = jest.fn()+ const consumer = buildConsumer(jest.fn().mockRejectedValue(new Error('network down')), queueLogs)+ const job = buildJob(lastAttemptState())++ await consumer.processResolverJob(job)++ expect(queueLogs).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ message: `Batch resolver failed: Audience fetch failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts`,+ }),+ ],+ 'hog_flow'+ )+ })+ })})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 c2dba52f3bcb..6bdfa13e7952 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@@ -16,7 +16,10 @@ import {deserializeResolverState,serializeResolverState,} from '../services/hogflows/batch-resolver.types'-import { HogFlowBatchPersonQueryService } from '../services/hogflows/hogflow-batch-person-query.service'+import {+ AudienceFetchTimeoutError,+ HogFlowBatchPersonQueryService,+} from '../services/hogflows/hogflow-batch-person-query.service'import { invocationToV2JobInit } from '../services/job-queue/job-queue-postgres-v2'import { CyclotronJobInvocationHogFlow } from '../types'import {@@ -28,6 +31,23 @@ import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filterinimport { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterBatchHogFlowTriggerFailed } from './metrics'+/**+ * Reason text for a permanently failed audience fetch. The text goes on the batch run's log+ * stream, so a timeout says what the customer can change. Any other error stays generic,+ * because its text describes our internals. Only the last attempt's error arrives here, and+ * the earlier attempts may have failed for another reason, so the text claims the timeout for+ * that attempt alone.+ */+const audienceFailureReason = (error: unknown): string => {+ if (error instanceof AudienceFetchTimeoutError) {+ return (+ `Audience query timed out after ${Math.round(error.timeoutMs / 1000)}s on the last of ` ++ `${MAX_RESOLVER_ATTEMPTS} attempts. Use fewer or simpler audience filters, or a smaller audience.`+ )+ }+ return `Audience fetch failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts`+}+const RETRY_BACKOFF_MS = 5_000const HEARTBEAT_INTERVAL_MS = 10_000@@ -293,11 +313,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServeerror: serializeError(err),})- await this.transitionToFailedTerminal(- job,- state,- `Audience fetch failed permanently after ${MAX_RESOLVER_ATTEMPTS} attempts`- )+ await this.transitionToFailedTerminal(job, state, audienceFailureReason(err))return}logger.warn('⚠️', `${this.name} - page fetch failed, will retry`, {diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.tsindex 5747a93ea1a3..a465f6acd6f3 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts@@ -1,7 +1,10 @@+import { register } from 'prom-client'+import { Team } from '~/types'import {AccountAudienceResponse,+ AudienceFetchTimeoutError,BlastRadiusPersonsResponse,BlastRadiusResponse,HogFlowBatchPersonQueryService,@@ -269,4 +272,73 @@ describe('HogFlowBatchPersonQueryService', () => {)})})+ describe('audience fetch timeouts', () => {+ const timeoutError = (): Error => {+ const error = new Error('The operation was aborted due to timeout')+ error.name = 'TimeoutError'+ return error+ }++ const timeoutCount = async (endpoint: string): Promise<number> => {+ const metric = await register.getSingleMetric('cdp_batch_hog_flow_audience_fetch_timeout')?.get()+ return metric?.values.find((value) => value.labels.endpoint === endpoint)?.value ?? 0+ }++ it.each([+ ['user_blast_radius', (service: HogFlowBatchPersonQueryService) => service.getBlastRadius(team, filters)],+ [+ 'user_blast_radius_persons',+ (service: HogFlowBatchPersonQueryService) => service.getBlastRadiusPersons(team, filters),+ ],+ ['account_audience', (service: HogFlowBatchPersonQueryService) => service.getAccountAudiencePage(team, {})],+ ])('reports a %s timeout as AudienceFetchTimeoutError and counts it', async (endpoint, call) => {+ const service = createService()+ const before = await timeoutCount(endpoint)++ fetchMock.mockResolvedValue({ fetchResponse: null, fetchError: timeoutError() })++ const error = await call(service).catch((err: unknown) => err)++ expect(error).toBeInstanceOf(AudienceFetchTimeoutError)+ expect(error).toMatchObject({ endpoint, timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS })+ expect((error as Error).message).toBe(+ `Audience fetch to ${endpoint} timed out after 30000ms. The audience query did not finish inside ` ++ `CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS.`+ )+ expect(await timeoutCount(endpoint)).toBe(before + 1)+ })++ it('reports an abort wrapped in cause as a timeout', async () => {+ const service = createService()+ const aborted = new Error('aborted')+ aborted.name = 'AbortError'++ fetchMock.mockResolvedValue({+ fetchResponse: null,+ fetchError: new Error('fetch failed', { cause: aborted }),+ })++ await expect(service.getBlastRadiusPersons(team, filters)).rejects.toBeInstanceOf(AudienceFetchTimeoutError)+ })++ it('keeps a transport error that is not a timeout unchanged', async () => {+ const service = createService()++ fetchMock.mockResolvedValue({ fetchResponse: null, fetchError: new Error('network down') })++ await expect(service.getBlastRadiusPersons(team, filters)).rejects.not.toBeInstanceOf(+ AudienceFetchTimeoutError+ )+ })++ it('names the endpoint when the fetch returns no response and no error', async () => {+ const service = createService()++ fetchMock.mockResolvedValue({ fetchResponse: null, fetchError: null })++ await expect(service.getBlastRadiusPersons(team, filters)).rejects.toThrow(+ 'Audience fetch to user_blast_radius_persons returned no response'+ )+ })+ })})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 2604c763ad46..b30c7c6e00f0 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,3 +1,5 @@+import { Counter } from 'prom-client'+import { InternalFetchService } from '~/common/services/internal-fetch'import { parseJSON } from '~/common/utils/json-parse'import { logger, serializeError } from '~/common/utils/logger'@@ -23,6 +25,45 @@ export interface AccountAudienceResponse {group_type: string}+const counterAudienceFetchTimeout = new Counter({+ name: 'cdp_batch_hog_flow_audience_fetch_timeout',+ help: 'An audience fetch for a batch hog flow exceeded its client-side timeout budget',+ labelNames: ['endpoint'],+})++export type AudienceFetchEndpoint = 'user_blast_radius' | 'user_blast_radius_persons' | 'account_audience'++/**+ * An audience fetch used its full CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS budget.+ * The client aborted the request. The query behind the endpoint keeps running server-side+ * until the HogQL execution cap, so a timeout means the query is too slow, and not that+ * Django is unreachable. The two failures need different operator action, so they get+ * different error types.+ */+export class AudienceFetchTimeoutError extends Error {+ override name = 'AudienceFetchTimeoutError'++ constructor(+ public readonly endpoint: AudienceFetchEndpoint,+ public readonly timeoutMs: number+ ) {+ super(+ `Audience fetch to ${endpoint} timed out after ${timeoutMs}ms. The audience query did not finish ` ++ `inside CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS.`+ )+ }+}++// AbortSignal.timeout rejects with a TimeoutError. undici reports some aborts as an+// AbortError, and can wrap either one in `cause`.+const TIMEOUT_ERROR_NAMES = ['TimeoutError', 'AbortError']++const isTimeoutError = (error: unknown): boolean => {+ const name = (error as { name?: string } | null)?.name+ const causeName = (error as { cause?: { name?: string } } | null)?.cause?.name+ return TIMEOUT_ERROR_NAMES.includes(name ?? '') || TIMEOUT_ERROR_NAMES.includes(causeName ?? '')+}+/*** Service for querying persons via Django internal API for batch HogFlow processing.* Calls internal endpoints authenticated with INTERNAL_API_SECRET.@@ -34,6 +75,31 @@ export class HogFlowBatchPersonQueryService {private audienceFetchTimeoutMs: number) {}+ /**+ * Raise the error the caller sees for a transport failure. A timeout gets its own error+ * type and its own counter, because the audience query is too slow for the budget. Any+ * other transport error keeps its original type.+ */+ private failFetch(endpoint: AudienceFetchEndpoint, urlPath: string, fetchError: Error | null): never {+ if (isTimeoutError(fetchError)) {+ counterAudienceFetchTimeout.labels({ endpoint }).inc()+ logger.error('Audience fetch timed out', {+ endpoint,+ urlPath,+ timeoutMs: this.audienceFetchTimeoutMs,+ error: serializeError(fetchError),+ })+ throw new AudienceFetchTimeoutError(endpoint, this.audienceFetchTimeoutMs)+ }++ logger.error('Error fetching audience from Django', {+ endpoint,+ urlPath,+ error: serializeError(fetchError),+ })+ throw fetchError ?? new Error(`Audience fetch to ${endpoint} returned no response`)+ }+/*** Get count of users affected by filters*/@@ -59,11 +125,7 @@ export class HogFlowBatchPersonQueryService {})if (!fetchResponse || fetchError) {- logger.error('Error fetching blast radius from Django', {- error: serializeError(fetchError),- urlPath,- })- throw fetchError+ this.failFetch('user_blast_radius', urlPath, fetchError)}if (fetchResponse.status !== 200) {@@ -116,11 +178,7 @@ export class HogFlowBatchPersonQueryService {})if (!fetchResponse || fetchError) {- logger.error('Error fetching blast radius persons from Django', {- error: serializeError(fetchError),- urlPath,- })- throw fetchError+ this.failFetch('user_blast_radius_persons', urlPath, fetchError)}if (fetchResponse.status !== 200) {@@ -166,11 +224,7 @@ export class HogFlowBatchPersonQueryService {})if (!fetchResponse || fetchError) {- logger.error('Error fetching account audience from Django', {- error: serializeError(fetchError),- urlPath,- })- throw fetchError+ this.failFetch('account_audience', urlPath, fetchError)}if (fetchResponse.status !== 200) {