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): bound rerun page-error retries to prevent smallint overflow (#71701)

posthog[bot]4009cf0488f2
diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts
index 588efd8ab135..566b87f5b2ba 100644
--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts
@@ -6,10 +6,10 @@ import { parseJSON } from '~/common/utils/json-parse'
import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'
import { resetTestDatabase } from '../../../tests/helpers/sql'
import { Hub } from '../../types'
-import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'
+import { RERUN_PAGE_ERROR_BACKOFF_MAX_MS, RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'
import { RerunJobQueues } from '../rerun/rerun-paginator.service'
import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'
-import { CdpRerunWorkerConsumer } from './cdp-rerun-worker.consumer'
+import { CdpRerunWorkerConsumer, pageRetryDelayMs } from './cdp-rerun-worker.consumer'
// Minimal stub for a job queue backend — the consumer only calls the producer
// lifecycle hooks; the paginator (which would call queueInvocations) is stubbed.
@@ -219,6 +219,20 @@ describe('CdpRerunWorkerConsumer', () => {
})
})
+ describe('pageRetryDelayMs', () => {
+ // A retry storm against a ClickHouse that is already degraded is what
+ // produces the streak in the first place, so the delay has to grow with
+ // it while a healthy page keeps the flat cadence.
+ it.each([
+ [0, 500],
+ [1, 1000],
+ [4, 8000],
+ [20, RERUN_PAGE_ERROR_BACKOFF_MAX_MS],
+ ])('delays %i consecutive errors by %ims', (consecutiveErrors, expected) => {
+ expect(pageRetryDelayMs(consecutiveErrors)).toBe(expected)
+ })
+ })
+
describe('isHealthy', () => {
it('returns an error result when stopping', () => {
consumer['isStopping'] = true
diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
index b723dfca262e..25a5edbfd535 100644
--- a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts
@@ -7,7 +7,7 @@ import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginsServerConfig } from '../../types'
-import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'
+import { RERUN_PAGE_ERROR_BACKOFF_MAX_MS, RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'
import { RerunJobQueues, RerunPaginatorService } from '../rerun/rerun-paginator.service'
import { CyclotronV2Worker } from '../services/cyclotron-v2'
import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'
@@ -21,6 +21,18 @@ const HEARTBEAT_INTERVAL_MS = 10_000
// the worker; cyclotron-v2 reschedule + dequeue overhead absorbs the wait anyway.
const RERUN_PAGE_DELAY_MS = 500
+/**
+ * Delay before retrying a page that errored, doubling per consecutive error up
+ * to `RERUN_PAGE_ERROR_BACKOFF_MAX_MS`. A healthy page (streak 0) keeps the
+ * flat `RERUN_PAGE_DELAY_MS`, so only the failing case slows down.
+ */
+export function pageRetryDelayMs(consecutiveErrors: number): number {
+ if (consecutiveErrors <= 0) {
+ return RERUN_PAGE_DELAY_MS
+ }
+ return Math.min(RERUN_PAGE_DELAY_MS * 2 ** consecutiveErrors, RERUN_PAGE_ERROR_BACKOFF_MAX_MS)
+}
+
const counterRerunJobsAcked = new Counter({
name: 'cdp_hog_invocation_rerun_jobs_acked_total',
help: 'Rerun wrapper jobs terminated by the worker, by outcome.',
@@ -185,7 +197,7 @@ export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig>
// Persist progress + reschedule for the next page.
await job.reschedule({
- scheduledAt: new Date(Date.now() + RERUN_PAGE_DELAY_MS),
+ scheduledAt: new Date(Date.now() + pageRetryDelayMs(nextState.progress.consecutive_errors ?? 0)),
state: Buffer.from(JSON.stringify(nextState)),
})
} catch (e) {
diff --git a/nodejs/src/cdp/rerun/rerun-job.types.ts b/nodejs/src/cdp/rerun/rerun-job.types.ts
index 90f6cfdd5e56..89839e3976e1 100644
--- a/nodejs/src/cdp/rerun/rerun-job.types.ts
+++ b/nodejs/src/cdp/rerun/rerun-job.types.ts
@@ -84,6 +84,15 @@ export interface RerunJobProgress {
done: boolean
/** Last error from a page; non-fatal — the next reschedule retries. */
last_error?: string
+ /**
+ * Consecutive page errors since the last page that made progress. Bumped on
+ * every errored page and reset to 0 whenever a page succeeds. Once it hits
+ * `RERUN_MAX_CONSECUTIVE_PAGE_ERRORS` the paginator gives up (throws) so the
+ * worker fails the wrapper job terminally instead of rescheduling it forever
+ * — an unbounded retry loop bumps the SMALLINT `transition_count` on every
+ * reschedule until it overflows (`smallint out of range`), poisoning the row.
+ */
+ consecutive_errors?: number
/**
* Number of pages that have committed progress to this job. Bumped per
* call to `processPage`. Surfaces on the wrapper lifecycle row as `attempts`
@@ -101,3 +110,28 @@ export interface RerunJobState {
/** Hard cap on rows fetched per rerun page (also caps a by-IDs request slice). */
export const RERUN_PAGE_SIZE = 200
+
+/**
+ * How many consecutive errored pages a rerun tolerates before the paginator
+ * gives up and fails the wrapper job terminally (recorded as a replayable
+ * failure). A single stuck page (malformed filter, undecodable globals,
+ * persistent ClickHouse error) otherwise reschedules indefinitely, and each
+ * reschedule increments the SMALLINT `transition_count` until it overflows at
+ * 32767, which then poisons the row so even dequeue fails.
+ *
+ * Sized together with `RERUN_PAGE_ERROR_BACKOFF_MAX_MS` so the budget outlasts
+ * a ClickHouse restart or failover: giving up on one of those permanently
+ * fails an otherwise-healthy rerun and loses its paged progress. A successful
+ * page resets the counter, so this bounds only an uninterrupted streak, and
+ * even a full streak stays two orders of magnitude below the SMALLINT ceiling.
+ */
+export const RERUN_MAX_CONSECUTIVE_PAGE_ERRORS = 200
+
+/**
+ * Ceiling for the exponential backoff the worker applies between retries of an
+ * errored page, growing from `RERUN_PAGE_DELAY_MS`. Retrying the same failing
+ * ClickHouse query at the healthy-page cadence adds load exactly when
+ * ClickHouse is already degraded, which is the condition most likely to have
+ * produced the streak in the first place.
+ */
+export const RERUN_PAGE_ERROR_BACKOFF_MAX_MS = 60_000
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
index 4e069e62010d..a12d6969408d 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
@@ -24,7 +24,7 @@ import { HogFunctionManagerService } from '../services/managers/hog-function-man
import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'
import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'
import { CyclotronJobInvocationHogFunction, HogFunctionInvocationGlobals, HogFunctionType } from '../types'
-import { RERUN_PAGE_SIZE, RerunJobState } from './rerun-job.types'
+import { RERUN_MAX_CONSECUTIVE_PAGE_ERRORS, RERUN_PAGE_SIZE, RerunJobState } from './rerun-job.types'
import { RerunPaginatorService } from './rerun-paginator.service'
const ActualKafkaProducerWrapper = jest.requireActual('~/common/kafka/producer').KafkaProducerWrapper
@@ -498,6 +498,32 @@ describe('RerunPaginatorService integration', () => {
expect(next.progress.done).toBe(true)
expect(hogQueue.queueInvocations).not.toHaveBeenCalled()
})
+
+ it('keeps a page successful when only the wrapper progress row fails to write', async () => {
+ // The page's invocations are committed before the wrapper row is
+ // written, so a failure there must not count toward the give-up
+ // streak — otherwise a lifecycle-write outage marks a rerun failed
+ // that actually ran, and holds the cursor back onto the same page.
+ await seedRows([{ invocation_id: 'inv-ok', status: 'succeeded' }])
+ jest.spyOn(paginatorLifecycleService, 'queueRerunWrapperRow').mockImplementation(() => {
+ throw new Error('lifecycle write boom')
+ })
+
+ const state = buildState({
+ request: {
+ filter: { window_start: '2026-01-01T00:00:00Z', window_end: '2027-01-01T00:00:00Z' },
+ },
+ })
+
+ const { state: next } = await paginator.processPage(team.id, state, {
+ jobId: 'test-rerun-job',
+ createdAt: DateTime.now(),
+ })
+
+ expect(next.progress.done).toBe(true)
+ expect(next.progress.last_error).toBeUndefined()
+ expect(next.progress.consecutive_errors).toBeUndefined()
+ })
})
describe('max_attempts filter (poison-pill autodrain path)', () => {
@@ -607,13 +633,11 @@ describe('RerunPaginatorService integration', () => {
})
describe('error handling', () => {
- it('captures a ClickHouse query error on progress.last_error without marking done', async () => {
- // Point the paginator at a deliberately broken ClickHouse client to
- // exercise the catch path.
+ const buildBrokenPaginator = (): RerunPaginatorService => {
const brokenChClient = {
query: jest.fn().mockRejectedValue(new Error('clickhouse boom')),
} as unknown as ClickHouseClient
- const brokenPaginator = new RerunPaginatorService(
+ return new RerunPaginatorService(
brokenChClient,
hogFunctionManager,
hogFlowManager,
@@ -622,8 +646,10 @@ describe('RerunPaginatorService integration', () => {
paginatorMonitoringService,
10000
)
+ }
- const state = buildState({
+ const brokenState = () =>
+ buildState({
request: {
filter: {
window_start: '2026-01-01T00:00:00Z',
@@ -634,14 +660,33 @@ describe('RerunPaginatorService integration', () => {
progress: { queued: 0, skipped: 0, done: false },
})
- const { state: next } = await brokenPaginator.processPage(team.id, state, {
+ it('captures a page error on progress.last_error, bumps the streak, and keeps the job running', async () => {
+ const { state: next } = await buildBrokenPaginator().processPage(team.id, brokenState(), {
jobId: 'test-rerun-job',
createdAt: DateTime.now(),
})
expect(next.progress.done).toBe(false)
expect(next.progress.last_error).toContain('clickhouse boom')
+ // Streak tracked so a persistently-failing page eventually gives up
+ // instead of rescheduling forever (which overflows transition_count).
+ expect(next.progress.consecutive_errors).toBe(1)
expect(hogQueue.queueInvocations).not.toHaveBeenCalled()
})
+
+ it('gives up (throws) once a page has errored RERUN_MAX_CONSECUTIVE_PAGE_ERRORS times', async () => {
+ // One more errored page past the cap must throw so the worker fails
+ // the wrapper job terminally — the guard against an unbounded retry
+ // loop that would drive the SMALLINT transition_count to overflow.
+ const state = brokenState()
+ state.progress.consecutive_errors = RERUN_MAX_CONSECUTIVE_PAGE_ERRORS - 1
+
+ await expect(
+ buildBrokenPaginator().processPage(team.id, state, {
+ jobId: 'test-rerun-job',
+ createdAt: DateTime.now(),
+ })
+ ).rejects.toThrow('clickhouse boom')
+ })
})
describe('done logic (real CH)', () => {
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
index af4fcfa217db..4f508201d153 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts
@@ -25,7 +25,13 @@ import {
RERUNNABLE_HOG_FUNCTION_TYPES,
} from '../types'
import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
-import { RERUN_PAGE_SIZE, RerunFunctionKind, RerunJobProgress, RerunJobState } from './rerun-job.types'
+import {
+ RERUN_MAX_CONSECUTIVE_PAGE_ERRORS,
+ RERUN_PAGE_SIZE,
+ RerunFunctionKind,
+ RerunJobProgress,
+ RerunJobState,
+} from './rerun-job.types'
const counterRerunPageProcessed = new Counter({
name: 'cdp_hog_invocation_rerun_pages_processed_total',
@@ -241,7 +247,19 @@ export class RerunPaginatorService {
// Update the wrapper lifecycle row + emit a progress log so the
// Invocations tab reflects the running total without the user
// hitting Refresh between pages.
- await this.writeWrapperUpdate(teamId, state, context, nextProgress, undefined)
+ //
+ // Best-effort: the page's invocations are already committed to kafka
+ // or postgres-v2 by this point, so letting a lifecycle-write failure
+ // reach the catch below would count a page that did its work as a
+ // page error, hold the cursor back, and on a persistent write outage
+ // eventually mark a rerun failed that actually ran.
+ await this.writeWrapperUpdate(teamId, state, context, nextProgress, undefined).catch((writeErr) => {
+ logger.warn('Rerun paginator could not write the wrapper progress row', {
+ rerun_function_kind: function_kind,
+ rerun_function_id: function_id,
+ error: writeErr instanceof Error ? writeErr.message : String(writeErr),
+ })
+ })
return { state: { ...state, progress: nextProgress } }
} catch (err) {
@@ -252,10 +270,22 @@ export class RerunPaginatorService {
error: errMessage,
})
counterRerunPageProcessed.labels(function_kind, 'error').inc()
- // Surface the error in job state but don't mark done — the worker
- // will reschedule, the janitor's transition_count guards against
- // infinite loops on poisoned jobs.
- const errorProgress = { ...progress, last_error: errMessage }
+
+ // Give up once a page has errored too many times in a row. Rethrow
+ // so the worker's handler fails the wrapper job terminally (and
+ // records a replayable failure row) rather than rescheduling. An
+ // unbounded retry loop would bump the SMALLINT `transition_count` on
+ // every reschedule until it overflows at 32767 — poisoning the row
+ // so even dequeue fails with `smallint out of range`.
+ const consecutiveErrors = (progress.consecutive_errors ?? 0) + 1
+ if (consecutiveErrors >= RERUN_MAX_CONSECUTIVE_PAGE_ERRORS) {
+ throw err
+ }
+
+ // Below the cap: surface the error in job state but don't mark done,
+ // so the worker reschedules and retries the same page. Track the
+ // consecutive-error streak — a page that later succeeds resets it.
+ const errorProgress = { ...progress, last_error: errMessage, consecutive_errors: consecutiveErrors }
await this.writeWrapperUpdate(teamId, state, context, errorProgress, err)
return { state: { ...state, progress: errorProgress } }
}