Skip to content

: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.

fix(cdp): give batch workflow audience resolution its own timeout (#93606)

jake sciotto524e48b8f95d
diff --git a/docs/internal/workflows-batch-audience-resolution.md b/docs/internal/workflows-batch-audience-resolution.md
new file mode 100644
index 000000000000..56838e5dcf62
--- /dev/null
+++ b/docs/internal/workflows-batch-audience-resolution.md
@@ -0,0 +1,37 @@
+# Batch workflow audience resolution
+
+How a batch-triggered workflow run resolves its audience, and the knobs that bound it.
+
+## The resolver
+
+Triggering a batch workflow creates one cyclotron job on `HOGFLOW_BATCH_RESOLVE_QUEUE`, processed by the `cdp-cyclotron-worker-batch-resolve` consumer. Each dequeue fetches one audience page from Django's internal endpoints (`user_blast_radius_persons` for person audiences, `account_audience` for account audiences), enqueues that page's runs, and reschedules itself with the next cursor until the audience is exhausted or truncated by `maxAudienceSize`. The terminal status (`completed`/`failed`) is PUT back to Django on a final dequeue, and the resolver only acks after that write succeeds.
+
+## Audience fetch timeout
+
+The page fetch runs a ClickHouse query, so it does not fit the generic 3s `EXTERNAL_REQUEST_TIMEOUT_MS` inter-service budget:
+
+- `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.
+
+## Lock heartbeats and batch size
+
+A near-budget fetch holds one job for ~30s, the same magnitude as the janitor's stall threshold (`CYCLOTRON_NODE_JANITOR_STALL_TIMEOUT_MS`, default 30s). Two things keep the janitor from reclaiming a healthy job:
+
+- The consumer heartbeats the held job every 10s while it processes.
+- It dequeues one job at a time (`batchMaxSize: 1`). Pages are processed serially, so a bigger batch adds no throughput — it only leaves queued peers un-heartbeated behind a slow fetch.
+
+Lease heartbeats update the job's database lock; they do not refresh the worker's poll health check.
+The worker waits for page processing to finish before polling again.
+Its `heartbeatTimeoutMs` adds 30 seconds to the audience fetch budget for processing and monitoring flushes.
+The default health timeout is 60 seconds.
+This keeps an allowed slow fetch from reporting the worker as unhealthy while its lease remains valid.
+
+## Observing
+
+- Fetch durations: `instrumented_function_duration_seconds` for `cdpBatchResolve.getBlastRadiusPersons` and `cdpBatchResolve.getAccountAudiencePage`. Watch the p99 against the budget before tuning either.
+- 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 app
+
+The resolver keys its failure, audience-truncation, and cancel logs by batch job id, but every in-app log reader queries by workflow id (`LogsViewer sourceId={workflow.id}`; the Logs panel of a batch workflow redirects to Invocations). Normal run logs use `log_source_id` = workflow id and `instance_id` = run id. So a batch run that fails before enrolling anyone shows only a `failed` badge, and the reason is only reachable by querying `log_entries` directly. Re-keying those three resolver log sites to `log_source_id: state.hogFlowId, instance_id: state.batchJobId` would make them appear in the workflow's Logs view and as the batch job's own log stream; that is a separate change from the timeout.
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.ts
index f5b85ca0fd4a..65af0b24c271 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,7 @@ 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 { BatchResolverState, serializeResolverState } from '../services/hogflows/batch-resolver.types'
import {
HogInvocationResultRow,
HogInvocationResultsService,
@@ -298,4 +298,83 @@ describe('CdpCyclotronWorkerBatchResolve', () => {
expect(flush).toHaveBeenCalled()
})
})
+
+ describe('resolver job lock heartbeats', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each([false, true])('clears the heartbeat timer (heartbeat fails: %s)', async (heartbeatFails) => {
+ jest.useFakeTimers()
+ const state: BatchResolverState = {
+ batchJobId: 'batch-job-hb',
+ 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',
+ }
+ // Long enough for two heartbeat ticks, inside the 30s default fetch budget.
+ const getBlastRadiusPersons = jest.fn().mockImplementation(async () => {
+ await new Promise<void>((resolve) => {
+ setTimeout(() => resolve(), 25_000)
+ })
+ return { users_affected: [], cursor: null, has_more: false }
+ })
+ 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 },
+ hogMasker: {
+ filterByMasking: jest.fn((invocations) => ({
+ masked: [],
+ notMasked: invocations,
+ release: jest.fn().mockResolvedValue(undefined),
+ })),
+ },
+ hogFunctionMonitoringService: {
+ queueAppMetrics: jest.fn(),
+ queueLogs: jest.fn(),
+ flush: jest.fn().mockResolvedValue(undefined),
+ },
+ invocationResultsService: {
+ invocationResultsRowsService: { flush: jest.fn().mockResolvedValue(undefined) },
+ },
+ })
+ const heartbeat = heartbeatFails
+ ? jest.fn().mockRejectedValue(new Error('Heartbeat unavailable'))
+ : jest.fn().mockResolvedValue(undefined)
+ const job = {
+ id: 'job-heartbeat',
+ teamId: team.id,
+ functionId: hogFlow.id,
+ parentRunId: 'batch-job-hb',
+ cancelRequestedAt: null,
+ state: serializeResolverState(state),
+ heartbeat,
+ bulkCreateAndCheckIn: jest.fn().mockResolvedValue({ newJobIds: [] }),
+ reschedule: jest.fn().mockResolvedValue(undefined),
+ ack: jest.fn().mockResolvedValue(undefined),
+ fail: jest.fn().mockResolvedValue(undefined),
+ }
+
+ const processPromise = (consumer as any).processResolverJob(job)
+ await jest.advanceTimersByTimeAsync(25_000)
+ await processPromise
+
+ expect(heartbeat).toHaveBeenCalledTimes(2)
+ expect(getBlastRadiusPersons).toHaveBeenCalledTimes(1)
+ expect(job.bulkCreateAndCheckIn).toHaveBeenCalledTimes(1)
+ expect(jest.getTimerCount()).toBe(0)
+ await jest.advanceTimersByTimeAsync(20_000)
+ expect(heartbeat).toHaveBeenCalledTimes(2)
+ })
+ })
})
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.ts
index 653905562e71..c2dba52f3bcb 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
@@ -29,6 +29,7 @@ import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'
import { counterBatchHogFlowTriggerFailed } from './metrics'
const RETRY_BACKOFF_MS = 5_000
+const HEARTBEAT_INTERVAL_MS = 10_000
const counterBatchHogFlowAudienceTruncated = new Counter({
name: 'cdp_batch_hog_flow_audience_truncated',
@@ -137,6 +138,19 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
counterBatchHogFlowResolverJobs.labels({ outcome: 'started' }).inc()
}
+ // Heartbeat the lock while the page (or terminal write) runs: the audience fetch alone
+ // can hold this job for the full CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS budget,
+ // which is on the order of the janitor's stall threshold — without heartbeats the
+ // janitor would reclaim the lock mid-page and the commit would be refused.
+ const heartbeat = setInterval(() => {
+ job.heartbeat().catch((err) => {
+ logger.warn('⚠️', `${this.name} - failed to heartbeat resolver job`, {
+ jobId: job.id,
+ error: String(err),
+ })
+ })
+ }, HEARTBEAT_INTERVAL_MS)
+
try {
if (state.pendingTerminal) {
try {
@@ -165,6 +179,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
await this.processOnePage(job, state)
} finally {
+ clearInterval(heartbeat)
// Flush monitoring every dequeue, not just on terminal-write. Non-terminal
// paths (truncation log queued in processOnePage, failure log in
// transitionToFailedTerminal) would otherwise wait for a later terminal
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.ts
index a549be0ac9f5..5747a93ea1a3 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
@@ -20,6 +20,8 @@ const createFetchResponse = (status: number, body: unknown): { status: number; t
}
}
+const AUDIENCE_FETCH_TIMEOUT_MS = 30_000
+
describe('HogFlowBatchPersonQueryService', () => {
const team = { id: 123 } as Team
const filters = { properties: [], filter_test_accounts: true }
@@ -31,7 +33,7 @@ describe('HogFlowBatchPersonQueryService', () => {
})
const createService = (): HogFlowBatchPersonQueryService => {
- return new HogFlowBatchPersonQueryService({ fetch: fetchMock } as any)
+ return new HogFlowBatchPersonQueryService({ fetch: fetchMock } as any, AUDIENCE_FETCH_TIMEOUT_MS)
}
describe('getBlastRadius', () => {
@@ -51,6 +53,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters,
group_type_index: 1,
@@ -73,6 +76,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters,
group_type_index: undefined,
@@ -139,6 +143,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius_persons',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters,
group_type_index: 2,
@@ -151,6 +156,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius_persons',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters,
group_type_index: 2,
@@ -182,6 +188,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius_persons',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters,
group_type_index: undefined,
@@ -240,6 +247,7 @@ describe('HogFlowBatchPersonQueryService', () => {
urlPath: '/api/projects/123/internal/hog_flows/account_audience',
fetchParams: {
method: 'POST',
+ timeoutMs: AUDIENCE_FETCH_TIMEOUT_MS,
body: JSON.stringify({
filters: accountFilters,
cursor: 'abc',
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.ts
index a8b2baef40fc..2604c763ad46 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
@@ -29,7 +29,10 @@ export interface AccountAudienceResponse {
* Endpoints: /internal/hog_flows/user_blast_radius and /internal/hog_flows/user_blast_radius_persons
*/
export class HogFlowBatchPersonQueryService {
- constructor(private internalFetchService: InternalFetchService) {}
+ constructor(
+ private internalFetchService: InternalFetchService,
+ private audienceFetchTimeoutMs: number
+ ) {}
/**
* Get count of users affected by filters
@@ -47,6 +50,7 @@ export class HogFlowBatchPersonQueryService {
urlPath,
fetchParams: {
method: 'POST',
+ timeoutMs: this.audienceFetchTimeoutMs,
body: JSON.stringify({
filters,
group_type_index: groupTypeIndex,
@@ -101,6 +105,7 @@ export class HogFlowBatchPersonQueryService {
urlPath,
fetchParams: {
method: 'POST',
+ timeoutMs: this.audienceFetchTimeoutMs,
body: JSON.stringify({
filters,
group_type_index: groupTypeIndex,
@@ -152,6 +157,7 @@ export class HogFlowBatchPersonQueryService {
urlPath,
fetchParams: {
method: 'POST',
+ timeoutMs: this.audienceFetchTimeoutMs,
body: JSON.stringify({
filters,
cursor: cursor || null,
diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.ts
index cfd6175c3a61..85ddce2ebe21 100644
--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts
@@ -4288,6 +4288,8 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {
pool: { dbUrl: CYCLOTRON_NODE_DB_URL, maxConnections: 10 },
queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
pollDelayMs: 100,
+ batchMaxSize: 1,
+ heartbeatTimeoutMs: hub.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS + 30_000,
})
// The consumer only calls connect/disconnect/isHealthy on the worker.
const workerForConsumer = wrapJob
@@ -4299,7 +4301,10 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {
} as unknown as CyclotronV2Worker)
: cyclotronWorker
const internalFetchService = new InternalFetchService(hub.INTERNAL_API_BASE_URL, hub.INTERNAL_API_SECRET)
- const queryService = new HogFlowBatchPersonQueryService(internalFetchService)
+ const queryService = new HogFlowBatchPersonQueryService(
+ internalFetchService,
+ hub.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS
+ )
return new CdpCyclotronWorkerBatchResolve(hub, deps, workerForConsumer, queryService, internalFetchService)
}
@@ -4519,6 +4524,85 @@ describe('Workflows E2E: batch resolver dispatch via cdp-api', () => {
}, 10000)
})
+ it('keeps the job lock and worker health during a slow audience fetch', async () => {
+ const flow = await insertActiveBatchFlow()
+ const parentRunId = new UUIDT().toString()
+ const personId = new UUIDT().toString()
+ const originalTimeout = hub.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS
+ hub.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS = 45_000
+ const audiencePage = Promise.withResolvers<void>()
+ const statusPuts: Array<{ status: string }> = []
+ let audienceCalls = 0
+ const janitor = new CyclotronV2Janitor({
+ pool: { dbUrl: CYCLOTRON_NODE_DB_URL },
+ stallTimeoutMs: 15_000,
+ maxTouchCount: 2,
+ cleanupGraceMs: 99_999_000,
+ cleanupBatchSize: 100,
+ cleanupIntervalMs: 60_000,
+ })
+
+ mockInternalFetch.mockImplementation(async (url: string, opts: any) => {
+ if (url.includes('/user_blast_radius_persons')) {
+ audienceCalls += 1
+ expect(opts.timeoutMs).toBe(45_000)
+ await audiencePage.promise
+ return {
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () =>
+ Promise.resolve(JSON.stringify({ users_affected: [personId], cursor: null, has_more: false })),
+ dump: async () => {},
+ }
+ }
+ if (url.includes('/batch_jobs/') && url.endsWith('/status')) {
+ statusPuts.push(parseJSON(opts.body) as { status: string })
+ return {
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve('{}'),
+ dump: async () => {},
+ }
+ }
+ throw new Error(`Unexpected internalFetch call to ${url}`)
+ })
+
+ try {
+ 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)
+
+ resolverWorker = buildResolverConsumer()
+ await resolverWorker.start()
+ await waitForExpect(() => expect(audienceCalls).toBe(1), 5000)
+ await new Promise((resolve) => setTimeout(resolve, 32_000))
+
+ expect(resolverWorker.isHealthy().status).toBe('ok')
+ const sweep = await janitor.runOnce()
+ expect(sweep.stalled).toBe(0)
+ expect(sweep.poisoned).toBe(0)
+
+ audiencePage.resolve()
+ await waitForExpect(() => expect(statusPuts).toEqual([{ status: 'completed' }]), 10_000)
+ expect(audienceCalls).toBe(1)
+ const jobs = await cyclotronPool.query(
+ 'SELECT queue_name, janitor_touch_count FROM cyclotron_jobs WHERE parent_run_id = $1',
+ [parentRunId]
+ )
+ expect(jobs.rows.filter((job) => job.queue_name === 'hogflow')).toHaveLength(1)
+ for (const job of jobs.rows) {
+ expect(job.janitor_touch_count).toBe(0)
+ }
+ } finally {
+ audiencePage.resolve()
+ hub.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS = originalTimeout
+ await janitor.stop()
+ }
+ }, 60_000)
+
// 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.
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index ff46924e133b..2cc459944ed5 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -240,6 +240,12 @@ export type CommonConfig = BaseServerConfig & {
// executeSync on the JS thread.
CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED: boolean
+ // Timeout for the internal audience-resolution calls a batch workflow makes while paging its
+ // target audience. These run ClickHouse queries that routinely take longer than the 3s
+ // EXTERNAL_REQUEST_TIMEOUT_MS inter-service budget, so they get a larger one of their own —
+ // without it, resolving a non-trivial audience always times out and the whole batch run fails.
+ CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS: number
+
/** Per-function wall-clock budget for an event transformation, enforced by the HogVM. */
TRANSFORMATIONS_HOG_TIMEOUT_MS: number
@@ -432,6 +438,7 @@ export function getDefaultCommonConfig(): CommonConfig {
// Shared between ingestion and CDP
CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED: false,
+ CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS: 30_000,
TRANSFORMATIONS_HOG_TIMEOUT_MS: 300,
// Event loop yield helper
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index b2e614d3c240..882cd0b5e1db 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -399,12 +399,20 @@ export class PluginServer implements NodeServer {
},
queueName: HOGFLOW_BATCH_RESOLVE_QUEUE,
pollDelayMs: 100,
+ heartbeatTimeoutMs: this.config.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS + 30_000,
+ // Pages are processed serially, so a bigger dequeue batch adds no throughput —
+ // it only leaves queued peers un-heartbeated behind a slow audience fetch until
+ // the janitor's stall sweep reclaims them. Same shape as the rerun worker.
+ batchMaxSize: 1,
})
const internalFetchService = new InternalFetchService(
this.config.INTERNAL_API_BASE_URL,
this.config.INTERNAL_API_SECRET
)
- const hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(internalFetchService)
+ const hogFlowBatchPersonQueryService = new HogFlowBatchPersonQueryService(
+ internalFetchService,
+ this.config.CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS
+ )
const consumer = new CdpCyclotronWorkerBatchResolve(
this.config,
cdpDeps!,
diff --git a/nodejs/tests/server.serial.test.ts b/nodejs/tests/server.serial.test.ts
index 083190b8fe7b..dea23ca5ac4b 100644
--- a/nodejs/tests/server.serial.test.ts
+++ b/nodejs/tests/server.serial.test.ts
@@ -46,6 +46,33 @@ describe('server', () => {
await pluginsServer.start()
})
+ it('keeps batch resolver healthy for the configured audience budget plus processing headroom', async () => {
+ pluginsServer = new PluginServer({
+ LOG_LEVEL: 'debug',
+ PLUGIN_SERVER_MODE: PluginServerMode.cdp_cyclotron_worker_batch_resolve,
+ PERSONHOG_ENABLED: true,
+ PERSONHOG_ADDR: 'localhost:50052',
+ CDP_HOG_FLOW_BATCH_AUDIENCE_FETCH_TIMEOUT_MS: 45_000,
+ })
+ await pluginsServer.start()
+ expect(process.exit).not.toHaveBeenCalledWith(1)
+
+ const service = pluginsServer.lifecycle.services.find(({ id }) => id === 'CdpCyclotronWorkerBatchResolve')
+ expect(service).toBeDefined()
+
+ const now = Date.now()
+ const dateNow = jest.spyOn(Date, 'now')
+ try {
+ dateNow.mockReturnValue(now + 65_000)
+ expect((await service!.healthcheck()).isError()).toBe(false)
+
+ dateNow.mockReturnValue(now + 80_000)
+ expect((await service!.healthcheck()).isError()).toBe(true)
+ } finally {
+ dateNow.mockRestore()
+ }
+ })
+
// Replay modes are handled by IngestionSessionReplayServer (see ingestion-session-replay-server.test.ts)
it('should error on startup with replay mode', async () => {
const server = new PluginServer({