: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
feat(cdp): node producer + rerun paginator (2/3) (#58825)
Ben Whiteab67fe7cf065
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex c1849abb47aa..26662c32a08a 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -17,6 +17,7 @@ export const CAPABILITIES_CDP: PluginServerCapabilities = {appManagementSingleton: true,cdpDataWarehouseEvents: false, // Not yet fully developed - enable when readycdpLegacyOnEvent: false, // most of the times not needed+ cdpRerunWorker: true,}/** CDP + Workflows - full CDP with HogFlow workflow automation */@@ -170,6 +171,10 @@ export function getPluginServerCapabilities(return {cdpCyclotronV2Janitor: true,}+ case PluginServerMode.cdp_rerun_worker:+ return {+ cdpRerunWorker: true,+ }case PluginServerMode.ingestion_v2:case PluginServerMode.ingestion_v2_testing:case PluginServerMode.ingestion_v2_combined:diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex b25387acf16c..ec1f44f98f44 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -24,6 +24,8 @@ import {} from './consumers/cdp-source-webhooks.consumer'import { HogTransformerService, createHogTransformerService } from './hog-transformations/hog-transformer.service'import { BATCH_HOGFLOW_REQUESTS_OUTPUT } from './outputs/outputs'+import { RerunJobManager } from './rerun/rerun-job.manager'+import { RerunRequest } from './rerun/rerun-job.types'import { BatchExportHogFunctionService, NotFoundError, ParseError } from './services/batch-export-hog-function.service'import { HogExecutorExecuteAsyncOptions, HogExecutorService, MAX_ASYNC_STEPS } from './services/hog-executor.service'import { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'@@ -81,6 +83,7 @@ export class CdpApi {private hogWatcher: HogWatcherServiceprivate hogTransformer: HogTransformerServiceprivate invocationResultsService: InvocationResultsService+ private rerunJobManager: RerunJobManager | null = nullprivate cdpSourceWebhooksConsumer: CdpSourceWebhooksConsumerprivate cyclotronJobQueue: CyclotronJobQueueprivate emailTrackingService: EmailTrackingService@@ -141,6 +144,19 @@ export class CdpApi {async start(): Promise<void> {await this.cdpSourceWebhooksConsumer.start()await this.cyclotronJobQueue.startAsProducer()++ // Rerun endpoints don't run the work — they just enqueue a wrapper+ // job onto the cyclotron-v2 'rerun' queue. A dedicated consumer+ // (`CdpRerunWorkerConsumer`) deployed as PLUGIN_SERVER_MODE=cdp-rerun-worker+ // pages ClickHouse, rehydrates invocations, and commits progress back+ // to the wrapper job via reschedule(state).+ if (this.config.CYCLOTRON_NODE_DATABASE_URL) {+ this.rerunJobManager = new RerunJobManager({+ dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL,+ maxCount: this.config.HOG_INVOCATION_RERUN_MAX_COUNT,+ })+ await this.rerunJobManager.connect()+ }}async stop(): Promise<void> {@@ -148,6 +164,7 @@ export class CdpApi {this.cdpSourceWebhooksConsumer.stop(),this.cyclotronJobQueue.stop(),this.batchExportHogFunctionService.stop(),+ this.rerunJobManager?.disconnect() ?? Promise.resolve(),])}@@ -175,6 +192,11 @@ export class CdpApi {'/api/projects/:team_id/hog_flows/:id/batch_invocations/:parent_run_id',asyncHandler(this.postHogFlowBatchInvocation))+ router.post(+ '/api/projects/:team_id/hog_functions/:id/rerun',+ asyncHandler(this.postRerunInvocations('hog_function'))+ )+ router.post('/api/projects/:team_id/hog_flows/:id/rerun', asyncHandler(this.postRerunInvocations('hog_flow')))router.get('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.getFunctionStatus()))router.patch('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.patchFunctionStatus()))router.get('/api/hog_functions/states', asyncHandler(this.getFunctionStates()))@@ -607,6 +629,88 @@ export class CdpApi {}}+ // Rerun endpoints don't run the work — they just enqueue a wrapper job+ // onto the cyclotron-v2 'rerun' queue. The dedicated `CdpRerunWorkerConsumer`+ // picks it up, pages ClickHouse, rehydrates invocations onto the regular+ // queue, and commits progress back to the wrapper job's state.+ private postRerunInvocations =+ (functionKind: 'hog_function' | 'hog_flow') =>+ async (req: ModifiedRequest, res: express.Response): Promise<any> => {+ try {+ if (!this.rerunJobManager) {+ return res.status(503).json({+ error: 'Rerun manager not initialized (CYCLOTRON_NODE_DATABASE_URL unset)',+ })+ }++ const { team_id, id } = req.params+ const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)+ if (!team) {+ return res.status(404).json({ error: 'Team not found' })+ }++ if (functionKind === 'hog_function') {+ const hogFunction = await this.hogFunctionManager.getHogFunction(id)+ if (!hogFunction || hogFunction.team_id !== team.id) {+ return res.status(404).json({ error: 'Hog function not found' })+ }+ } else {+ const hogFlow = await this.hogFlowManager.getHogFlow(id)+ if (!hogFlow || hogFlow.team_id !== team.id) {+ return res.status(404).json({ error: 'Hog flow not found' })+ }+ }++ const rerunRequest = req.body as RerunRequest+ const rerunJobId = await this.rerunJobManager.enqueue(team.id, functionKind, id, rerunRequest)++ // Surface the wrapper job in the Invocations list immediately —+ // a 'running' lifecycle row + a `rerun_queued` log line. Both+ // share the same `instance_id = rerun_job_id` so the logs+ // viewer in the row's expand panel picks them up automatically.+ const now = new Date()+ this.invocationResultsService.invocationResultsRowsService.queueRerunWrapperRow({+ teamId: team.id,+ parentFunctionKind: functionKind,+ functionId: id,+ rerunJobId,+ status: 'running',+ pagesProcessed: 0,+ filter: rerunRequest.filter,+ scheduledAt: now,+ startedAt: now,+ })+ this.invocationResultsService.monitoringService.queueLogs(+ [+ {+ team_id: team.id,+ log_source: functionKind,+ log_source_id: id,+ instance_id: rerunJobId,+ timestamp: DateTime.fromJSDate(now),+ level: 'info',+ message: `Re-run queued. Filter: ${JSON.stringify(rerunRequest.filter)}`,+ },+ ],+ functionKind+ )+ await this.invocationResultsService.flush()++ logger.info('⚡️', 'Rerun job enqueued', {+ function_kind: functionKind,+ function_id: id,+ team_id: team.id,+ rerun_job_id: rerunJobId,+ })+ res.json({ rerun_job_id: rerunJobId, queued_count: 0, skipped_count: 0 })+ } catch (e) {+ logger.error('Error enqueueing rerun job', {+ error: e instanceof Error ? e.message : String(e),+ })+ res.status(500).json({ error: e instanceof Error ? e.message : String(e) })+ }+ }+private postHogFlowBatchInvocation = async (req: ModifiedRequest, res: express.Response): Promise<any> => {try {const { id, team_id, parent_run_id } = req.paramsdiff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex bd0c2bb0d689..4103f9d9cbc4 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -3,7 +3,7 @@ import { getRedisHost } from '~/utils/db/redis'import type { CommonConfig } from '../common/config'import { InternalCaptureService } from '../common/services/internal-capture'-import { AppMetricsOutput, LogEntriesOutput } from '../ingestion/common/outputs'+import { AppMetricsOutput, HogInvocationResultsOutput, LogEntriesOutput } from '../ingestion/common/outputs'import { IngestionOutputs } from '../ingestion/outputs/ingestion-outputs'import { KafkaProducerRegistry } from '../ingestion/outputs/kafka-producer-registry'import { PostgresRouter } from '../utils/db/postgres'@@ -35,6 +35,7 @@ import { EmailService } from './services/messaging/email.service'import { RecipientPreferencesService } from './services/messaging/recipient-preferences.service'import { RecipientTokensService } from './services/messaging/recipient-tokens.service'import { HogFunctionMonitoringService } from './services/monitoring/hog-function-monitoring.service'+import { HogInvocationResultsService } from './services/monitoring/hog-invocation-results.service'import { HogWatcherService } from './services/monitoring/hog-watcher.service'import { NativeDestinationExecutorService } from './services/native-destination-executor.service'import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'@@ -45,6 +46,7 @@ import { EncryptedFields } from './utils/encryption-utils'export type CdpOutput =| AppMetricsOutput| LogEntriesOutput+ | HogInvocationResultsOutput| PrefilteredEventsOutput| PrecalculatedPersonPropertiesOutput| BatchHogflowRequestsOutput@@ -78,12 +80,16 @@ export interface CdpCoreServices {*/hogWatcherMirror: HogWatcherService | nullhogExecutor: HogExecutorService+ /** Rebuilds the templated/resolved input bundle for a hog function — used by the rerun path to re-derive `inputs` after they're stripped from the persisted payload. */+ hogInputsService: HogInputsServicehogFunctionTemplateManager: HogFunctionTemplateManagerServicehogFlowFunctionsService: HogFlowFunctionsServicerecipientsManager: RecipientsManagerServicerecipientPreferencesService: RecipientPreferencesServicehogFlowExecutor: HogFlowExecutorServicehogFunctionMonitoringService: HogFunctionMonitoringService+ /** Per-invocation lifecycle row producer for the new runs/invocations UI + rerun path. */+ hogInvocationResultsService: HogInvocationResultsService/** Fans `CyclotronJobInvocationResult` batches across monitoring / warehouse / captured-events. */invocationResultsService: InvocationResultsServicenativeDestinationExecutorService: NativeDestinationExecutorService@@ -138,6 +144,9 @@ export type CdpCoreServicesConfig = Pick<| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC'| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_PRODUCER'+ | 'HOG_INVOCATION_RESULTS_TOPIC'+ | 'HOG_INVOCATION_RESULTS_PRODUCER'+ | 'HOG_INVOCATION_RESULTS_ENABLED'| 'CDP_PREFILTERED_EVENTS_TOPIC'| 'CDP_PREFILTERED_EVENTS_PRODUCER'| 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC'@@ -411,10 +420,12 @@ export function createCdpCoreServices(const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)const hogFunctionMonitoringService = new HogFunctionMonitoringService(outputs)+ const hogInvocationResultsService = new HogInvocationResultsService(outputs, config)const warehouseWebhooksService = new WarehouseWebhooksService(outputs)const capturedEventsService = new CapturedEventsService(deps.internalCaptureService, deps.teamManager)const invocationResultsService = new InvocationResultsService(hogFunctionMonitoringService,+ hogInvocationResultsService,warehouseWebhooksService,capturedEventsService)@@ -430,12 +441,14 @@ export function createCdpCoreServices(hogWatcher,hogWatcherMirror,hogExecutor,+ hogInputsService,hogFunctionTemplateManager,hogFlowFunctionsService,recipientsManager,recipientPreferencesService,hogFlowExecutor,hogFunctionMonitoringService,+ hogInvocationResultsService,invocationResultsService,nativeDestinationExecutorService,segmentDestinationExecutorService,diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 580845190a68..2a51e17d1beb 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -1,9 +1,11 @@+import { ClickhouseConfig, getDefaultClickhouseConfig } from '../common/clickhouse-config'import {KAFKA_APP_METRICS_2,KAFKA_CDP_BATCH_HOGFLOW_REQUESTS,KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,KAFKA_EVENTS_JSON,+ KAFKA_HOG_INVOCATION_RESULTS,KAFKA_LOG_ENTRIES,KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,} from '../config/kafka-topics'@@ -17,7 +19,10 @@ import {} from './outputs/producers'import { CyclotronJobQueueKind, CyclotronJobQueueSource } from './types'-export type CdpConfig = {+// CdpConfig intersects ClickhouseConfig so any consumer reading+// `this.config.CLICKHOUSE_HOST` etc. gets typed, defaulted values — fixes the+// case where `CdpRerunWorkerConsumer` silently fell back to `default` DB.+export type CdpConfig = ClickhouseConfig & {CDP_WATCHER_COST_ERROR: numberCDP_WATCHER_HOG_COST_TIMING: numberCDP_WATCHER_HOG_COST_TIMING_LOWER_MS: number@@ -88,6 +93,10 @@ export type CdpConfig = {HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER: CdpProducerNameHOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC: stringHOG_FUNCTION_MONITORING_LOG_ENTRIES_PRODUCER: CdpProducerName+ HOG_INVOCATION_RESULTS_TOPIC: string+ HOG_INVOCATION_RESULTS_PRODUCER: CdpProducerName+ HOG_INVOCATION_RESULTS_ENABLED: boolean+ HOG_INVOCATION_RERUN_MAX_COUNT: numberCDP_PREFILTERED_EVENTS_TOPIC: stringCDP_PREFILTERED_EVENTS_PRODUCER: CdpProducerNameCDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: string@@ -127,6 +136,7 @@ export type CdpConfig = {export function getDefaultCdpConfig(): CdpConfig {return {+ ...getDefaultClickhouseConfig(),CDP_WATCHER_COST_ERROR: 100,CDP_WATCHER_HOG_COST_TIMING: 100,CDP_WATCHER_HOG_COST_TIMING_LOWER_MS: 50,@@ -191,6 +201,17 @@ export function getDefaultCdpConfig(): CdpConfig {HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC: KAFKA_LOG_ENTRIES,HOG_FUNCTION_MONITORING_LOG_ENTRIES_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,+ HOG_INVOCATION_RESULTS_TOPIC: KAFKA_HOG_INVOCATION_RESULTS,+ // Cyclotron Warpstream cluster — ClickHouse consumes hog_invocation_results+ // from the warpstream_cyclotron named collection, so the producer must+ // target the same cluster.+ HOG_INVOCATION_RESULTS_PRODUCER: WARPSTREAM_CYCLOTRON_PRODUCER,+ // Off by default — flip to true once the table is migrated and we want to start writing.+ // Per-team rollout still happens at the call site.+ HOG_INVOCATION_RESULTS_ENABLED: isDevEnv() ? true : false,+ // Hard cap on rows a single rerun wrapper job will drain. Mirrors the+ // Django serializer's HOG_INVOCATION_RERUN_MAX_COUNT (same env var).+ HOG_INVOCATION_RERUN_MAX_COUNT: 10000,CDP_PREFILTERED_EVENTS_TOPIC: KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,CDP_PREFILTERED_EVENTS_PRODUCER: WARPSTREAM_CALCULATED_EVENTS_PRODUCER,CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC: KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES,diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 5c92a27f5ea1..d88de1b75bf3 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -16,6 +16,7 @@ import {} from '../cdp-services'import type { CdpConfig } from '../config'import { HogExecutorService } from '../services/hog-executor.service'+import { HogInputsService } from '../services/hog-inputs.service'import { HogFlowExecutorService } from '../services/hogflows/hogflow-executor.service'import { HogFlowFunctionsService } from '../services/hogflows/hogflow-functions.service'import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'@@ -55,6 +56,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = CdisStopping = falsehogExecutor: HogExecutorService+ hogInputsService: HogInputsServicehogFlowExecutor: HogFlowExecutorServicehogMasker: HogMaskerServicehogWatcher: HogWatcherService@@ -91,6 +93,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.hogWatcher = services.hogWatcherthis.hogWatcherMirror = services.hogWatcherMirrorthis.hogExecutor = services.hogExecutor+ this.hogInputsService = services.hogInputsServicethis.hogFunctionTemplateManager = services.hogFunctionTemplateManagerthis.hogFlowFunctionsService = services.hogFlowFunctionsServicethis.recipientsManager = services.recipientsManagerdiff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 7dc1f64e5751..61c02d98eac6 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -75,6 +75,17 @@ export class CdpEventsConsumer<...(await this.createHogFlowInvocations(invocationGlobals)),]+ // Emit a `running` lifecycle row for each freshly-created invocation.+ // This fires ONCE per invocation_id at creation — not on every dequeue+ // — so the runs UI can show in-flight work without us writing duplicate+ // running rows across fetch retries. The terminal row is queued later+ // by the cyclotron worker; both collapse under the same `invocation_id`+ // via ReplacingMergeTree, with the terminal row's later `version`+ // superseding the running row on FINAL queries.+ for (const invocation of invocationsToBeQueued) {+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }+return {// This is all IO so we can set them off in the background and start processing the next batchbackgroundTask: Promise.all([@@ -89,6 +100,9 @@ export class CdpEventsConsumer<logger.error('🔴', 'Error producing queued messages for monitoring', { err })}}),+ instrumentFn({ key: 'cdp.background_task.lifecycle_running_flush', sendException: false }, () =>+ this.invocationResultsService.invocationResultsRowsService.flush()+ ),]),invocations: invocationsToBeQueued,}diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.tsnew file mode 100644index 000000000000..5e5a5c65e8c6--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.test.ts@@ -0,0 +1,225 @@+import { DateTime } from 'luxon'++import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'+import { resetTestDatabase } from '../../../tests/helpers/sql'+import { Hub } from '../../types'+import { closeHub, createHub } from '../../utils/db/hub'+import { parseJSON } from '../../utils/json-parse'+import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'+import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CdpRerunWorkerConsumer } from './cdp-rerun-worker.consumer'++jest.setTimeout(20000)++const buildDequeuedJob = (overrides: Partial<CyclotronV2DequeuedJob> = {}): jest.Mocked<CyclotronV2DequeuedJob> => {+ return {+ id: overrides.id ?? 'wrapper-job-1',+ teamId: overrides.teamId ?? 7,+ functionId: overrides.functionId ?? 'fn-1',+ queueName: RERUN_QUEUE_NAME,+ priority: 0,+ scheduled: DateTime.now(),+ created: DateTime.now(),+ parentRunId: null,+ transitionCount: 1,+ state: overrides.state ?? null,+ distinctId: null,+ personId: null,+ actionId: null,+ ack: jest.fn().mockResolvedValue(undefined),+ fail: jest.fn().mockResolvedValue(undefined),+ reschedule: jest.fn().mockResolvedValue(undefined),+ cancel: jest.fn().mockResolvedValue(undefined),+ heartbeat: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<CyclotronV2DequeuedJob>+}++const buildState = (overrides: Partial<RerunJobState> = {}): RerunJobState => ({+ function_kind: 'hog_function',+ function_id: 'fn-1',+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-1'],+ },+ },+ progress: { queued: 0, skipped: 0, done: false },+ ...overrides,+})++const jobWithState = (state: RerunJobState): jest.Mocked<CyclotronV2DequeuedJob> =>+ buildDequeuedJob({ state: Buffer.from(JSON.stringify(state)) })++describe('CdpRerunWorkerConsumer', () => {+ let consumer: CdpRerunWorkerConsumer+ let hub: Hub+ let mockProcessPage: jest.Mock++ beforeEach(async () => {+ await resetTestDatabase()+ hub = await createHub()+ // The worker needs the cyclotron-v2 node db to exist; pretend it does so the+ // consumer constructs cleanly. Real queue interactions are mocked below.+ hub.CYCLOTRON_NODE_DATABASE_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'++ consumer = new CdpRerunWorkerConsumer(hub, createCdpConsumerDeps(hub))++ // Replace the paginator with a stub so we exercise the consumer's+ // ack/reschedule/fail decisions without hitting ClickHouse. The catch+ // path also calls `writeWrapperFailure` so the stub stubs that too.+ mockProcessPage = jest.fn()+ consumer['paginator'] = {+ processPage: mockProcessPage,+ writeWrapperFailure: jest.fn().mockResolvedValue(undefined),+ } as any++ // We don't want the consumer to actually start the cyclotron worker loop or+ // the cyclotronJobQueue producer plumbing during these tests.+ consumer['worker'] = null+ consumer['cyclotronJobQueue'] = {+ startAsProducer: jest.fn(() => Promise.resolve()),+ stop: jest.fn(() => Promise.resolve()),+ } as unknown as jest.Mocked<CyclotronJobQueue>+ })++ afterEach(async () => {+ // stop() touches the worker and cyclotron client; both are stubbed/null above.+ await consumer.stop().catch(() => undefined)+ await closeHub(hub)+ })++ describe('handleJob', () => {+ it('acks the wrapper job when the paginator returns done=true', async () => {+ const state = buildState()+ const job = jobWithState(state)+ mockProcessPage.mockResolvedValue({+ state: { ...state, progress: { ...state.progress, done: true, queued: 1 } },+ })++ await consumer['handleJob'](job)++ expect(job.ack).toHaveBeenCalledTimes(1)+ expect(job.reschedule).not.toHaveBeenCalled()+ expect(job.fail).not.toHaveBeenCalled()+ })++ it('reschedules the wrapper job with updated state when the paginator returns done=false', async () => {+ const state = buildState()+ const job = jobWithState(state)+ const nextState: RerunJobState = {+ ...state,+ progress: {+ ...state.progress,+ cursor: { scheduled_at: '2026-05-01 00:00:00.000000', invocation_id: 'last' },+ queued: 200,+ done: false,+ },+ }+ mockProcessPage.mockResolvedValue({ state: nextState })++ await consumer['handleJob'](job)++ expect(job.ack).not.toHaveBeenCalled()+ expect(job.fail).not.toHaveBeenCalled()+ expect(job.reschedule).toHaveBeenCalledTimes(1)+ const rescheduleArg = job.reschedule.mock.calls[0][0]!+ expect(rescheduleArg.scheduledAt).toBeInstanceOf(Date)+ // Persisted state matches the new state returned by the paginator.+ const persisted = parseJSON(rescheduleArg.state!.toString('utf8')) as RerunJobState+ expect(persisted.progress.queued).toBe(200)+ expect(persisted.progress.cursor).toEqual(nextState.progress.cursor)+ })++ it('fails the wrapper job when state JSON is malformed', async () => {+ const job = buildDequeuedJob({ state: Buffer.from('not-json{') })++ await consumer['handleJob'](job)++ expect(job.fail).toHaveBeenCalledTimes(1)+ expect(mockProcessPage).not.toHaveBeenCalled()+ })++ it('fails the wrapper job when state is missing entirely', async () => {+ const job = buildDequeuedJob({ state: null })++ await consumer['handleJob'](job)++ expect(job.fail).toHaveBeenCalledTimes(1)+ expect(mockProcessPage).not.toHaveBeenCalled()+ })++ it('fails the wrapper job when the paginator throws', async () => {+ const state = buildState()+ const job = jobWithState(state)+ mockProcessPage.mockRejectedValue(new Error('paginator exploded'))++ await consumer['handleJob'](job)++ expect(job.fail).toHaveBeenCalledTimes(1)+ expect(job.ack).not.toHaveBeenCalled()+ expect(job.reschedule).not.toHaveBeenCalled()+ })++ it('heartbeats during a long-running page so the cyclotron lock does not expire', async () => {+ jest.useFakeTimers()+ const state = buildState()+ const job = jobWithState(state)++ // Make processPage take long enough for two heartbeat ticks.+ mockProcessPage.mockImplementation(async () => {+ await new Promise<void>((resolve) => {+ setTimeout(() => resolve(), 25_000)+ })+ return { state: { ...state, progress: { ...state.progress, done: true } } }+ })++ const handlePromise = consumer['handleJob'](job)+ await jest.advanceTimersByTimeAsync(25_000)+ await handlePromise++ expect(job.heartbeat).toHaveBeenCalled()+ expect(job.heartbeat.mock.calls.length).toBeGreaterThanOrEqual(2)+ jest.useRealTimers()+ })++ it('fails the job when the paginator field is unset (defensive guard)', async () => {+ consumer['paginator'] = null+ const state = buildState()+ const job = jobWithState(state)++ await consumer['handleJob'](job)++ expect(job.fail).toHaveBeenCalledTimes(1)+ })+ })++ describe('handleBatch', () => {+ it('drives every job in the batch through handleJob in order', async () => {+ const state = buildState()+ mockProcessPage.mockResolvedValue({ state: { ...state, progress: { ...state.progress, done: true } } })++ const jobs = [jobWithState(state), jobWithState({ ...state, function_id: 'fn-2' })]+ await consumer['handleBatch'](jobs)++ for (const job of jobs) {+ expect(job.ack).toHaveBeenCalledTimes(1)+ }+ expect(mockProcessPage).toHaveBeenCalledTimes(2)+ })+ })++ describe('isHealthy', () => {+ it('returns an error result when stopping', () => {+ consumer['isStopping'] = true+ expect(consumer.isHealthy().isError()).toBe(true)+ })++ it('returns an error result when the worker is missing', () => {+ consumer['isStopping'] = false+ consumer['worker'] = null+ expect(consumer.isHealthy().isError()).toBe(true)+ })+ })+})diff --git a/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.tsnew file mode 100644index 000000000000..e9cba6e0d847--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-rerun-worker.consumer.ts@@ -0,0 +1,232 @@+import { ClickHouseClient, createClient as createClickHouseClient } from '@clickhouse/client'+import https from 'https'+import { Counter } from 'prom-client'++import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginsServerConfig } from '../../types'+import { parseJSON } from '../../utils/json-parse'+import { logger } from '../../utils/logger'+import { captureException } from '../../utils/posthog'+import { RERUN_QUEUE_NAME, RerunJobState } from '../rerun/rerun-job.types'+import { RerunPaginatorService } from '../rerun/rerun-paginator.service'+import { CyclotronV2Worker } from '../services/cyclotron-v2'+import { CyclotronV2DequeuedJob } from '../services/cyclotron-v2/types'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'++// Heartbeat interval — the cyclotron-v2 lock timeout is 30s by default, send+// roughly twice that often so a slow ClickHouse page doesn't lose the lock.+const HEARTBEAT_INTERVAL_MS = 10_000++// Delay between pages of the same rerun job. Keeps a long rerun from hot-looping+// the worker; cyclotron-v2 reschedule + dequeue overhead absorbs the wait anyway.+const RERUN_PAGE_DELAY_MS = 500++const counterRerunJobsAcked = new Counter({+ name: 'cdp_hog_invocation_rerun_jobs_acked_total',+ help: 'Rerun wrapper jobs terminated by the worker, by outcome.',+ labelNames: ['outcome'],+})++/**+ * Consumes the cyclotron-v2 'rerun' queue and drives the rerun paginator.+ *+ * Each dequeued job carries a `RerunJobState` blob describing one user's+ * rerun request (by ids or by filter). The worker:+ * 1. Parses the state.+ * 2. Runs one page of ClickHouse + rehydrate + enqueue work via `RerunPaginatorService`.+ * 3. If `progress.done` → `ack()` the wrapper job (terminal).+ * Otherwise → `reschedule({ state: updatedState, scheduledAt: now + RERUN_PAGE_DELAY_MS })`+ * so the next worker iteration picks it back up.+ *+ * Deploy with `PLUGIN_SERVER_MODE=cdp-rerun-worker`. Multiple replicas are+ * safe — cyclotron-v2 uses `FOR UPDATE SKIP LOCKED`.+ */+export class CdpRerunWorkerConsumer extends CdpConsumerBase<PluginsServerConfig> {+ protected name = 'CdpRerunWorkerConsumer'++ private worker: CyclotronV2Worker | null = null+ private cyclotronJobQueue: CyclotronJobQueue+ private paginator: RerunPaginatorService | null = null+ private clickhouseClient: ClickHouseClient | null = null++ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps) {+ super(config, deps)+ // Used by the paginator to re-enqueue invocations as it pages.+ this.cyclotronJobQueue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ }++ override async start(): Promise<void> {+ if (!this.config.CYCLOTRON_NODE_DATABASE_URL) {+ throw new Error('CYCLOTRON_NODE_DATABASE_URL is required for the rerun worker')+ }++ await this.cyclotronJobQueue.startAsProducer()++ // Dedicated ClickHouse client for the paginator. The cluster's certs+ // are issued for an internal hostname that doesn't match the one we+ // dial in (`CLICKHOUSE_HOST` is typically a service-discovery name),+ // so we override `checkServerIdentity` to no-op the hostname check+ // while leaving the rest of the chain — signature, CA trust, expiry —+ // verified. This is a narrower bypass than `rejectUnauthorized: false`,+ // which would accept any cert from any signer.+ const chScheme = this.config.CLICKHOUSE_SECURE ? 'https' : 'http'+ const chPort = this.config.CLICKHOUSE_SECURE ? 8443 : 8123+ this.clickhouseClient = createClickHouseClient({+ url: `${chScheme}://${this.config.CLICKHOUSE_HOST}:${chPort}`,+ username: this.config.CLICKHOUSE_USER,+ password: this.config.CLICKHOUSE_PASSWORD || undefined,+ database: this.config.CLICKHOUSE_DATABASE,+ request_timeout: 60_000,+ max_open_connections: 10,+ ...(this.config.CLICKHOUSE_SECURE+ ? {+ http_agent: new https.Agent({+ keepAlive: true,+ maxSockets: 10,+ // Hostname-only bypass — full chain validation still runs.+ checkServerIdentity: () => undefined,+ }),+ }+ : {}),+ })++ this.paginator = new RerunPaginatorService(+ this.clickhouseClient,+ this.hogFunctionManager,+ this.hogFlowManager,+ // Used at rerun time to rebuild `inputs` (the templated/resolved+ // input bundle including secrets) from the current hog function+ // config, since we strip `inputs` from the persisted globals.+ this.hogInputsService,+ this.invocationResultsService.invocationResultsRowsService,+ this.cyclotronJobQueue,+ this.invocationResultsService.monitoringService,+ this.config.HOG_INVOCATION_RERUN_MAX_COUNT+ )++ this.worker = new CyclotronV2Worker({+ pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL },+ queueName: RERUN_QUEUE_NAME,+ // Rerun jobs are heavy (each runs a full ClickHouse query) — pull+ // them one at a time so a single replica can be deployed at high+ // concurrency without overwhelming ClickHouse.+ batchMaxSize: 1,+ pollDelayMs: 1000,+ })++ await this.worker.connect((jobs) => this.handleBatch(jobs))++ logger.info('🎬', 'CdpRerunWorkerConsumer started', { queue: RERUN_QUEUE_NAME })+ }++ override async stop(): Promise<void> {+ this.isStopping = true+ await this.worker?.disconnect()+ await this.cyclotronJobQueue.stop()+ await this.clickhouseClient?.close()+ await this.invocationResultsService.flush()+ }++ override isHealthy(): HealthCheckResult {+ if (this.isStopping) {+ return new HealthCheckResultError('CdpRerunWorkerConsumer is stopping', {})+ }+ if (!this.worker || !this.worker.isHealthy()) {+ return new HealthCheckResultError('CdpRerunWorkerConsumer worker not healthy', {})+ }+ return new HealthCheckResultOk()+ }++ override get service() {+ return {+ id: 'cdp-rerun-worker',+ onShutdown: () => this.stop(),+ healthcheck: () => this.isHealthy(),+ }+ }++ private async handleBatch(jobs: CyclotronV2DequeuedJob[]): Promise<void> {+ // batchMaxSize=1, so this is effectively one job at a time. The loop+ // exists for symmetry with other consumer base classes.+ for (const job of jobs) {+ await this.handleJob(job)+ }+ }++ private async handleJob(job: CyclotronV2DequeuedJob): Promise<void> {+ if (!this.paginator) {+ await job.fail()+ return+ }++ const state = this.parseState(job)+ if (!state) {+ logger.error('Rerun job has malformed state — failing', { job_id: job.id })+ counterRerunJobsAcked.labels('malformed').inc()+ await job.fail()+ return+ }++ // Heartbeat the lock while the page is running. ClickHouse queries+ // can take longer than the 30s default lock timeout for big windows.+ const heartbeat = setInterval(() => {+ job.heartbeat().catch((e) => {+ logger.warn('Failed to heartbeat rerun job', { job_id: job.id, error: String(e) })+ })+ }, HEARTBEAT_INTERVAL_MS)++ const context = { jobId: job.id, createdAt: job.created }+ try {+ const outcome = await this.paginator.processPage(job.teamId, state, context)+ const nextState = outcome.state++ if (nextState.progress.done) {+ logger.info('🎬', 'Rerun job complete', {+ job_id: job.id,+ team_id: job.teamId,+ queued: nextState.progress.queued,+ skipped: nextState.progress.skipped,+ })+ counterRerunJobsAcked.labels('done').inc()+ await job.ack()+ return+ }++ // Persist progress + reschedule for the next page.+ await job.reschedule({+ scheduledAt: new Date(Date.now() + RERUN_PAGE_DELAY_MS),+ state: Buffer.from(JSON.stringify(nextState)),+ })+ } catch (e) {+ logger.error('Rerun worker error processing job — failing', {+ job_id: job.id,+ error: e instanceof Error ? e.message : String(e),+ })+ captureException(e)+ counterRerunJobsAcked.labels('error').inc()+ // Surface the terminal failure on the Invocations tab before we+ // ack the cyclotron job — otherwise the wrapper row would be left+ // stuck on `status='running'` forever.+ await this.paginator?.writeWrapperFailure(job.teamId, state, context, e).catch((logErr) => {+ logger.error('Rerun worker failed to write wrapper failure row', {+ job_id: job.id,+ error: logErr instanceof Error ? logErr.message : String(logErr),+ })+ })+ await job.fail()+ } finally {+ clearInterval(heartbeat)+ }+ }++ private parseState(job: CyclotronV2DequeuedJob): RerunJobState | null {+ if (!job.state) {+ return null+ }+ try {+ return parseJSON(job.state.toString('utf8')) as RerunJobState+ } catch {+ return null+ }+ }+}diff --git a/nodejs/src/cdp/outputs/registry.ts b/nodejs/src/cdp/outputs/registry.tsindex 533c59916f39..3e5c10468b15 100644--- a/nodejs/src/cdp/outputs/registry.ts+++ b/nodejs/src/cdp/outputs/registry.ts@@ -1,4 +1,4 @@-import { APP_METRICS_OUTPUT, LOG_ENTRIES_OUTPUT } from '../../ingestion/common/outputs'+import { APP_METRICS_OUTPUT, HOG_INVOCATION_RESULTS_OUTPUT, LOG_ENTRIES_OUTPUT } from '../../ingestion/common/outputs'import { IngestionOutputsBuilder } from '../../ingestion/outputs/ingestion-outputs-builder'import {BATCH_HOGFLOW_REQUESTS_OUTPUT,@@ -30,6 +30,10 @@ export function createCdpOutputsRegistry() {topicKey: 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC',producerKey: 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_PRODUCER',})+ .register(HOG_INVOCATION_RESULTS_OUTPUT, {+ topicKey: 'HOG_INVOCATION_RESULTS_TOPIC',+ producerKey: 'HOG_INVOCATION_RESULTS_PRODUCER',+ }).register(PREFILTERED_EVENTS_OUTPUT, {topicKey: 'CDP_PREFILTERED_EVENTS_TOPIC',producerKey: 'CDP_PREFILTERED_EVENTS_PRODUCER',diff --git a/nodejs/src/cdp/rerun/rerun-e2e.test.ts b/nodejs/src/cdp/rerun/rerun-e2e.test.tsnew file mode 100644index 000000000000..5e4a505ef308--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-e2e.test.ts@@ -0,0 +1,335 @@+import { MockKafkaProducerWrapper } from '~/tests/helpers/mocks/producer.mock'+import { mockFetch } from '~/tests/helpers/mocks/request.mock'++import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'++import { DateTime } from 'luxon'+import { Pool } from 'pg'++import { createCdpConsumerDeps } from '~/tests/helpers/cdp'+import { Clickhouse } from '~/tests/helpers/clickhouse'+import { waitForExpect } from '~/tests/helpers/expectations'+import { ensureKafkaTopics, resetKafka } from '~/tests/helpers/kafka'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'++import { KAFKA_HOG_INVOCATION_RESULTS, KAFKA_INGESTION_WARNINGS } from '../../config/kafka-topics'+import { KafkaProducerWrapper } from '../../kafka/producer'+import { Hub, Team } from '../../types'+import { closeHub, createHub } from '../../utils/db/hub'+import { HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'+import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'+import { CdpCyclotronWorker } from '../consumers/cdp-cyclotron-worker.consumer'+import { CdpEventsConsumer } from '../consumers/cdp-events.consumer'+import { CdpRerunWorkerConsumer } from '../consumers/cdp-rerun-worker.consumer'+import { compileHog } from '../templates/compiler'+import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'+import { RerunJobManager } from './rerun-job.manager'+import { RERUN_QUEUE_NAME } from './rerun-job.types'++const ActualKafkaProducerWrapper = jest.requireActual('../../kafka/producer').KafkaProducerWrapper++const NODE_DB_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'++interface PersistedRow {+ invocation_id: string+ status: string+ is_retry: number+ attempts: number+ error_kind: string+ function_kind: string+}++/**+ * Probe the ClickHouse Kafka MV for our topic in particular. resetKafka()+ * deletes and recreates the topic, which forces the MV's internal consumer to+ * reconnect; with auto.offset.reset=latest, anything produced before the+ * reconnect is silently dropped. Send probe rows until one lands in CH so we+ * know the MV is live.+ */+const waitForHogInvocationResultsMvReady = async (clickhouse: Clickhouse): Promise<void> => {+ const producer = await ActualKafkaProducerWrapper.create(undefined)+ const probeTeamId = -999_999+ try {+ await waitForExpect(async () => {+ await producer.queueMessages({+ topic: KAFKA_HOG_INVOCATION_RESULTS,+ messages: [+ {+ key: 'probe',+ value: JSON.stringify({+ team_id: probeTeamId,+ function_kind: 'hog_function',+ function_id: 'probe',+ invocation_id: 'probe',+ parent_run_id: '',+ status: 'running',+ attempts: 0,+ is_retry: 0,+ scheduled_at: DateTime.utc().toFormat("yyyy-MM-dd HH:mm:ss.SSS'000'"),+ started_at: null,+ finished_at: null,+ duration_ms: null,+ error_kind: '',+ error_message: '',+ event_uuid: '',+ distinct_id: '',+ person_id: '',+ invocation_globals: '{}',+ version: String(BigInt(Date.now()) * 1000n),+ is_deleted: 0,+ }),+ },+ ],+ })+ await producer.flush()++ const result = await clickhouse.query<{ c: number }>(+ `SELECT count() AS c FROM hog_invocation_results WHERE team_id = ${probeTeamId}`+ )+ expect(Number(result[0]?.c ?? 0)).toBeGreaterThan(0)+ }, 30_000)+ } finally {+ await producer.disconnect()+ }+}++/**+ * End-to-end exercise of the runs/rerun pipeline.+ *+ * Everything is real: real Kafka, real ClickHouse Kafka MV, real cyclotron-v2+ * postgres, real cyclotron worker, real rerun wrapper-job loop. The ONLY thing+ * mocked is the inbound Django request — we call `RerunJobManager.enqueue(...)`+ * directly with the same payload the Django view would proxy through.+ *+ * Flow under test:+ * 1. Hog function runs -> producer writes a 'succeeded' lifecycle row to+ * Kafka -> MV lands it in `hog_invocation_results`.+ * 2. Simulated Django POST: `rerunManager.enqueue({ invocation_ids })`.+ * 3. Real `CdpRerunWorkerConsumer` dequeues the wrapper job, queries the+ * real `hog_invocation_results`, rehydrates globals (rebuilding inputs),+ * and re-enqueues onto the regular cyclotron queue.+ * 4. The real cyclotron worker picks up the rerun invocation and writes a+ * second lifecycle row, this time with `is_retry=1` and `attempts > 1`.+ */+describe('CDP hog invocation rerun e2e', () => {+ jest.setTimeout(60_000)++ let hub: Hub+ let kafkaProducer: KafkaProducerWrapper+ let team: Team+ let fnFetch: HogFunctionType+ let globals: HogFunctionInvocationGlobals+ let mockProducerObserver: KafkaProducerObserver+ let eventsConsumer: CdpEventsConsumer+ let cyclotronWorker: CdpCyclotronWorker+ let rerunManager: RerunJobManager+ let rerunWorker: CdpRerunWorkerConsumer+ let nodeAssertPool: Pool+ let clickhouse: Clickhouse++ beforeAll(() => {+ clickhouse = Clickhouse.create()+ })++ afterAll(() => {+ clickhouse?.close()+ jest.useRealTimers()+ })++ beforeEach(async () => {+ // Use a real KafkaProducerWrapper per the cdp-e2e pattern — gives us a+ // real producer to observe via KafkaProducerObserver.+ MockKafkaProducerWrapper.create = jest.fn((...args: any[]) => ActualKafkaProducerWrapper.create(...args))++ await resetKafka()+ // resetKafka does not include KAFKA_HOG_INVOCATION_RESULTS — add it so the+ // ClickHouse Kafka engine consumer can attach.+ await ensureKafkaTopics([KAFKA_HOG_INVOCATION_RESULTS, KAFKA_INGESTION_WARNINGS])+ await clickhouse.truncate('hog_invocation_results_data')+ await waitForHogInvocationResultsMvReady(clickhouse)+ await resetTestDatabase()+ await clickhouse.truncate('hog_invocation_results_data')++ hub = await createHub()+ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ mockProducerObserver = new KafkaProducerObserver(kafkaProducer)++ team = await getFirstTeam(hub.postgres)+ mockProducerObserver.resetKafkaProducer()++ hub.CDP_FETCH_RETRIES = 0+ hub.CDP_FETCH_BACKOFF_BASE_MS = 1+ hub.CDP_CYCLOTRON_COMPRESS_KAFKA_DATA = true+ hub.CYCLOTRON_DATABASE_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron'+ hub.CYCLOTRON_NODE_DATABASE_URL = NODE_DB_URL+ hub.HOG_INVOCATION_RESULTS_ENABLED = true+ // Route via cyclotron-v2 so the rerun path exercises the ON CONFLICT+ // upsert (rerun re-enqueue uses the original invocation_id, which+ // would otherwise collide on the cyclotron_jobs PK).+ hub.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = '*:postgres-v2'++ // Clean any stale rerun wrapper jobs from prior runs.+ nodeAssertPool = new Pool({ connectionString: NODE_DB_URL })+ await nodeAssertPool.query('DELETE FROM cyclotron_jobs WHERE queue_name = $1', [RERUN_QUEUE_NAME])++ const hog = `+ let res := fetch(inputs.url, {+ 'headers': { 'Content-Type': 'application/json' },+ 'body': inputs.body,+ 'method': inputs.method+ });+ print('Fetch response:', res);+ `++ fnFetch = await _insertHogFunction(hub.postgres, team.id, {+ type: 'destination',+ hog,+ bytecode: await compileHog(hog),+ inputs_schema: HOG_INPUTS_EXAMPLES.simple_fetch.inputs_schema ?? [],+ inputs: HOG_INPUTS_EXAMPLES.simple_fetch.inputs,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })++ const cyclotronConfig = { ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres-v2' as const }++ eventsConsumer = new CdpEventsConsumer(cyclotronConfig, createCdpConsumerDeps(hub, kafkaProducer))+ // We call processBatch directly — no need to actually join the kafka group.+ // Stubbing keeps the test off Redpanda's stale-group-protocol coordinator,+ // which otherwise fails the join with "Inconsistent group protocol".+ eventsConsumer['kafkaConsumer'] = {+ connect: jest.fn(),+ disconnect: jest.fn(),+ isHealthy: jest.fn(),+ } as any+ await eventsConsumer.start()++ cyclotronWorker = new CdpCyclotronWorker(cyclotronConfig, createCdpConsumerDeps(hub, kafkaProducer))+ await cyclotronWorker.start()++ rerunManager = new RerunJobManager({ dbUrl: NODE_DB_URL, maxCount: 10000 })+ await rerunManager.connect()++ globals = createHogExecutionGlobals({+ project: { id: team.id } as any,+ event: {+ uuid: '0d0ff14e-1b15-4afe-99e3-1ea83f0e3aab',+ event: '$pageview',+ properties: { $current_url: 'https://posthog.com' },+ timestamp: '2026-05-10T09:00:00Z',+ } as any,+ })+ })++ afterEach(async () => {+ await Promise.all([+ eventsConsumer?.stop().catch(() => undefined),+ cyclotronWorker?.stop().catch(() => undefined),+ rerunWorker?.stop().catch(() => undefined),+ rerunManager?.disconnect().catch(() => undefined),+ ])+ await kafkaProducer?.disconnect()+ await closeHub(hub)+ await nodeAssertPool.end()+ mockProducerObserver?.resetKafkaProducer()+ })++ it('produces a succeeded lifecycle row, then reruns the invocation via the wrapper-job pipeline', async () => {+ // ── 1. Original invocation succeeds ─────────────────────────────────+ mockFetch.mockResolvedValue({+ status: 200,+ json: () => Promise.resolve({ ok: true }),+ text: () => Promise.resolve('{"ok":true}'),+ headers: { 'Content-Type': 'application/json' },+ dump: () => Promise.resolve(),+ })++ const { invocations } = await eventsConsumer.processBatch([globals])+ expect(invocations).toHaveLength(1)++ // Wait for the terminal 'succeeded' row to flow Kafka -> MV -> ClickHouse.+ await waitForExpect(async () => {+ const rows = await clickhouse.query<PersistedRow>(+ `SELECT invocation_id, status, is_retry, attempts, error_kind, function_kind+ FROM hog_invocation_results+ WHERE team_id = ${team.id} AND function_id = '${fnFetch.id}' AND status = 'succeeded'`+ )+ expect(rows.length).toBeGreaterThanOrEqual(1)+ }, 30_000)++ const originalRows = await clickhouse.query<PersistedRow>(+ `SELECT invocation_id, status, is_retry, attempts, error_kind, function_kind+ FROM hog_invocation_results+ WHERE team_id = ${team.id} AND function_id = '${fnFetch.id}' AND status = 'succeeded'`+ )+ const originalInvocationId = originalRows[0].invocation_id+ expect(originalRows[0].is_retry).toBe(0)+ expect(originalRows[0].function_kind).toBe('hog_function')+ // The prior cyclotron_jobs row is in a terminal 'completed' state by+ // this point. The rerun path's `overwriteExisting: true` upsert+ // (cyclotron-v2 ON CONFLICT) handles the PK collision without us+ // having to manually delete the row.++ // ── 2. Mimic Django POST /rerun — only the request itself is faked ──────+ // The rerun request requires a time window; we use a wide one and+ // restrict to a specific invocation_id via the optional filter field.+ const rerunJobId = await rerunManager.enqueue(team.id, 'hog_function', fnFetch.id, {+ filter: {+ window_start: '2026-05-01T00:00:00Z',+ window_end: '2026-05-31T00:00:00Z',+ status: ['succeeded'],+ invocation_ids: [originalInvocationId],+ },+ })++ // Wrapper job is real and durable in test_cyclotron_node postgres.+ const wrapperRow = await nodeAssertPool.query(+ 'SELECT id, queue_name, status FROM cyclotron_jobs WHERE id = $1',+ [rerunJobId]+ )+ expect(wrapperRow.rows[0]).toMatchObject({+ id: rerunJobId,+ queue_name: RERUN_QUEUE_NAME,+ status: 'available',+ })++ // ── 3. Rerun worker drains the wrapper job ────────────────────────────────+ rerunWorker = new CdpRerunWorkerConsumer(+ { ...hub, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'postgres' },+ createCdpConsumerDeps(hub, kafkaProducer)+ )+ await rerunWorker.start()++ // ── 4. Wait for the wrapper job to complete ────────────────────────────────+ await waitForExpect(async () => {+ const res = await nodeAssertPool.query('SELECT status FROM cyclotron_jobs WHERE id = $1', [rerunJobId])+ // 'completed' = the paginator marked done=true and the worker acked.+ expect(res.rows[0]?.status).toBe('completed')+ }, 30_000)++ // ── 5. Reruned invocation flows through the real cyclotron worker ─────────+ // The paginator emits a 'running' row at re-enqueue time and the worker+ // emits the terminal row when the rerun invocation completes. Both+ // rows now correctly carry `is_retry=1` / `attempts=1` because the+ // paginator sets `state.rerunAttempts=1` on the rehydrated invocation+ // and `queueLifecycleRow` derives those columns from that field.+ await waitForExpect(async () => {+ const rows = await clickhouse.query<PersistedRow>(+ `SELECT invocation_id, status, is_retry, attempts, error_kind, function_kind+ FROM hog_invocation_results+ WHERE team_id = ${team.id}+ AND function_id = '${fnFetch.id}'+ AND invocation_id = '${originalInvocationId}'+ AND is_retry = 1`+ )+ // Either the paginator's running row, the worker's terminal row,+ // or both should be present and tagged is_retry=1.+ expect(rows.length).toBeGreaterThanOrEqual(1)+ for (const row of rows) {+ expect(row.attempts).toBe(1)+ }+ }, 30_000)++ // ── 6. The hog function's fetch was called twice — once original, once rerun ─+ expect(mockFetch.mock.calls.length).toBeGreaterThanOrEqual(2)+ })+})diff --git a/nodejs/src/cdp/rerun/rerun-job.manager.test.ts b/nodejs/src/cdp/rerun/rerun-job.manager.test.tsnew file mode 100644index 000000000000..45e00727d9c7--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-job.manager.test.ts@@ -0,0 +1,150 @@+import { Pool } from 'pg'+import { v7 as uuidv7 } from 'uuid'++import { parseJSON } from '../../utils/json-parse'+import { RerunJobManager } from './rerun-job.manager'+import { RERUN_QUEUE_NAME, RerunJobState } from './rerun-job.types'++const DB_URL = 'postgres://posthog:posthog@localhost:5432/test_cyclotron_node'+const TEST_MAX_COUNT = 1000++describe('RerunJobManager', () => {+ let assertPool: Pool+ let manager: RerunJobManager++ beforeAll(async () => {+ assertPool = new Pool({ connectionString: DB_URL })+ manager = new RerunJobManager({ dbUrl: DB_URL, maxCount: TEST_MAX_COUNT })+ await manager.connect()+ })++ afterAll(async () => {+ await manager.disconnect()+ await assertPool.end()+ })++ beforeEach(async () => {+ await assertPool.query('DELETE FROM cyclotron_jobs WHERE queue_name = $1', [RERUN_QUEUE_NAME])+ })++ interface RawJobRow {+ id: string+ team_id: number+ function_id: string | null+ queue_name: string+ status: string+ state: Buffer | null+ }++ const queryJob = async (id: string): Promise<RawJobRow> => {+ const res = await assertPool.query<RawJobRow>('SELECT * FROM cyclotron_jobs WHERE id = $1', [id])+ expect(res.rows).toHaveLength(1)+ return res.rows[0]+ }++ const fetchState = (row: RawJobRow): RerunJobState => {+ expect(row.state).not.toBeNull()+ return parseJSON(row.state!.toString('utf8')) as RerunJobState+ }++ const baseFilter = {+ window_start: '2026-05-01T00:00:00Z',+ window_end: '2026-05-10T00:00:00Z',+ }++ it('enqueues a wrapper job on the rerun queue with correct identity columns', async () => {+ const functionId = uuidv7()+ const ids = ['inv-1', 'inv-2', 'inv-3']++ const jobId = await manager.enqueue(42, 'hog_function', functionId, {+ filter: { ...baseFilter, invocation_ids: ids },+ })++ const row = await queryJob(jobId)+ expect(row.queue_name).toBe(RERUN_QUEUE_NAME)+ expect(row.status).toBe('available')+ expect(row.team_id).toBe(42)+ // function_id on the wrapper job lets metrics group it alongside the+ // invocations it spawns.+ expect(row.function_id).toBe(functionId)+ })++ it('serializes the request shape into state with a window-relative cursor stub', async () => {+ const functionId = uuidv7()+ const ids = ['a', 'b', 'c']++ const jobId = await manager.enqueue(7, 'hog_function', functionId, {+ filter: { ...baseFilter, invocation_ids: ids },+ })++ const state = fetchState(await queryJob(jobId))+ expect(state.function_kind).toBe('hog_function')+ expect(state.function_id).toBe(functionId)+ expect(state.request.filter.invocation_ids).toEqual(ids)+ expect(state.request.filter.window_start).toBe(baseFilter.window_start)+ expect(state.progress).toEqual({+ queued: 0,+ skipped: 0,+ // undefined cursor signals "start from the top of the window".+ cursor: undefined,+ done: false,+ })+ })++ it('trims oversized invocation_ids lists to the server-side cap', async () => {+ const ids = Array.from({ length: TEST_MAX_COUNT + 50 }, (_, i) => `id-${i}`)++ const jobId = await manager.enqueue(1, 'hog_function', uuidv7(), {+ filter: { ...baseFilter, invocation_ids: ids },+ })++ const state = fetchState(await queryJob(jobId))+ expect(state.request.filter.invocation_ids).toHaveLength(TEST_MAX_COUNT)+ })++ it('serializes a window-only request (no invocation_ids) with undefined cursor', async () => {+ const filter = {+ ...baseFilter,+ status: ['failed' as const],+ error_kind: ['http_5xx'],+ max_attempts: 3,+ max_count: 500,+ }++ const jobId = await manager.enqueue(3, 'hog_flow', uuidv7(), { filter })++ const state = fetchState(await queryJob(jobId))+ expect(state.function_kind).toBe('hog_flow')+ expect(state.request.filter).toMatchObject(filter)+ expect(state.request.filter.invocation_ids).toBeUndefined()+ expect(state.progress.cursor).toBeUndefined()+ expect(state.progress.done).toBe(false)+ })++ it('rejects a window longer than the TTL (30 days)', async () => {+ await expect(+ manager.enqueue(1, 'hog_function', uuidv7(), {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2026-12-31T00:00:00Z',+ },+ })+ ).rejects.toThrow(/cannot exceed 30 days/i)+ })++ it('rejects when window_end is before window_start', async () => {+ await expect(+ manager.enqueue(1, 'hog_function', uuidv7(), {+ filter: { window_start: '2026-05-10T00:00:00Z', window_end: '2026-05-01T00:00:00Z' },+ })+ ).rejects.toThrow(/window_end must be after window_start/i)+ })++ it('returns a uuidv7 for the job id', async () => {+ const jobId = await manager.enqueue(1, 'hog_function', uuidv7(), {+ filter: { ...baseFilter, invocation_ids: ['x'] },+ })+ // uuidv7 conforms to the standard UUID format+ expect(jobId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/)+ })+})diff --git a/nodejs/src/cdp/rerun/rerun-job.manager.ts b/nodejs/src/cdp/rerun/rerun-job.manager.tsnew file mode 100644index 000000000000..b625455d699e--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-job.manager.ts@@ -0,0 +1,120 @@+import { v7 as uuidv7 } from 'uuid'++import { logger } from '../../utils/logger'+import { CyclotronV2Manager } from '../services/cyclotron-v2'+import {+ RERUN_MAX_WINDOW_DAYS,+ RERUN_QUEUE_NAME,+ RerunFunctionKind,+ RerunJobState,+ RerunRequest,+} from './rerun-job.types'++export interface RerunJobManagerConfig {+ dbUrl: string+ maxConnections?: number+ idleTimeoutMs?: number+ depthLimit?: number+ /** Mirror of the Django serializer cap (HOG_INVOCATION_RERUN_MAX_COUNT env var). */+ maxCount: number+}++/**+ * Thin wrapper around `CyclotronV2Manager` for creating rerun wrapper jobs.+ *+ * Kept separate from `CyclotronJobQueuePostgresV2` (which marshals the+ * `CyclotronJobInvocation` shape) because the rerun job's `state` blob is a+ * `RerunJobState`, not an invocation. The consumer (`CdpRerunWorkerConsumer`)+ * pulls jobs from the same `cyclotron_jobs` table via its own `CyclotronV2Worker`+ * scoped to `queueName='rerun'`.+ */+export class RerunJobManager {+ private manager: CyclotronV2Manager++ constructor(private config: RerunJobManagerConfig) {+ this.manager = new CyclotronV2Manager({+ pool: {+ dbUrl: config.dbUrl,+ maxConnections: config.maxConnections,+ idleTimeoutMs: config.idleTimeoutMs,+ },+ depthLimit: config.depthLimit,+ })+ }++ async connect(): Promise<void> {+ await this.manager.connect()+ }++ async disconnect(): Promise<void> {+ await this.manager.disconnect()+ }++ /**+ * Create a new rerun wrapper job. Returns the cyclotron job id —+ * downstream callers (the Django API, eventually a status-poll endpoint)+ * use it to look up progress.+ */+ async enqueue(+ teamId: number,+ functionKind: RerunFunctionKind,+ functionId: string,+ request: RerunRequest+ ): Promise<string> {+ // Both bounds are required. Window can't exceed the ClickHouse TTL on+ // hog_invocation_results — older data is already gone via part drop.+ const start = new Date(request.filter.window_start)+ const end = new Date(request.filter.window_end)+ if (isNaN(start.getTime()) || isNaN(end.getTime())) {+ throw new Error('window_start and window_end must be valid ISO 8601 timestamps')+ }+ if (end.getTime() <= start.getTime()) {+ throw new Error('window_end must be after window_start')+ }+ const maxWindowMs = RERUN_MAX_WINDOW_DAYS * 24 * 60 * 60 * 1000+ if (end.getTime() - start.getTime() > maxWindowMs) {+ throw new Error(`rerun window cannot exceed ${RERUN_MAX_WINDOW_DAYS} days (TTL on hog_invocation_results)`)+ }++ const trimmedIds = request.filter.invocation_ids?.slice(0, this.config.maxCount)+ const filter = { ...request.filter, invocation_ids: trimmedIds }++ const state: RerunJobState = {+ function_kind: functionKind,+ function_id: functionId,+ request: { filter },+ progress: {+ queued: 0,+ skipped: 0,+ // Keyset cursor on (scheduled_at, invocation_id). undefined =>+ // start from the top of the window.+ cursor: undefined,+ done: false,+ },+ }++ const jobId = uuidv7()+ await this.manager.createJob({+ id: jobId,+ teamId,+ // function_id on the job row lets the janitor's by-function metrics+ // group rerun jobs alongside the invocations they spawn.+ functionId,+ queueName: RERUN_QUEUE_NAME,+ state: Buffer.from(JSON.stringify(state)),+ })++ logger.info('🎬', 'Enqueued rerun job', {+ rerun_job_id: jobId,+ team_id: teamId,+ function_kind: functionKind,+ function_id: functionId,+ mode: trimmedIds ? 'window_ids' : 'window_filter',+ window_start: filter.window_start,+ window_end: filter.window_end,+ requested_ids_count: trimmedIds?.length ?? 0,+ })++ return jobId+ }+}diff --git a/nodejs/src/cdp/rerun/rerun-job.types.ts b/nodejs/src/cdp/rerun/rerun-job.types.tsnew file mode 100644index 000000000000..90f6cfdd5e56--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-job.types.ts@@ -0,0 +1,103 @@+/**+ * Rerun job — the wrapper job that drives a paginated rerun of past hog+ * function or hog flow invocations.+ *+ * Two paths produce these:+ * 1. The Django→Node `/rerun` endpoint creates one with `progress.done=false`+ * and the user's request (either explicit ids or filter).+ * 2. The `CdpRerunWorkerConsumer` dequeues it, runs one page of work, and+ * either acks (done) or `reschedule({ state })` with updated progress.+ *+ * Why cyclotron-v2 instead of running inline in the API request:+ * - A by-filter rerun can match millions of rows. We can't block on it.+ * - Resumable: each page persists `progress.cursor` so a crash during a+ * long rerun picks up where it left off rather than from the top.+ * - Observable: the wrapper row in cyclotron_jobs surfaces in-flight+ * reruns + their progress via the same machinery as every other job.+ */++export const RERUN_QUEUE_NAME = 'rerun'++export type RerunFunctionKind = 'hog_function' | 'hog_flow'++/**+ * `function_kind` value we stamp on the wrapper row that the worker writes to+ * `hog_invocation_results` to surface a re-run in the Invocations UI alongside+ * the function's normal invocations. Suffixing avoids overloading the existing+ * kind enum and keeps "is this a wrapper?" a trivial check on the frontend.+ */+export type RerunWrapperFunctionKind = 'hog_function_rerun' | 'hog_flow_rerun'++export const rerunWrapperKindFor = (kind: RerunFunctionKind): RerunWrapperFunctionKind =>+ kind === 'hog_flow' ? 'hog_flow_rerun' : 'hog_function_rerun'++export const isRerunWrapperKind = (kind: string): kind is RerunWrapperFunctionKind =>+ kind === 'hog_function_rerun' || kind === 'hog_flow_rerun'++export type RerunStatusValue = 'running' | 'succeeded' | 'failed'++/**+ * Filter shape for a rerun request.+ *+ * `window_start` / `window_end` are REQUIRED — the lifecycle table is+ * partitioned by `toYYYYMMDD(scheduled_at)`, so a query without a time bound+ * scans every partition (up to 30 of them, since the TTL drops parts older+ * than that). The window also caps rerun to data that's still resident in the+ * table — older rows are gone via TTL anyway.+ *+ * `invocation_ids` is an OPTIONAL additional restriction. When set, the+ * paginator pulls only those ids within the window — a UI "rerun these+ * specific failed runs" affordance. Server-side cap on the list size is+ * enforced via `HOG_INVOCATION_RERUN_MAX_COUNT`.+ */+export interface RerunFilter {+ window_start: string+ window_end: string+ status?: RerunStatusValue[]+ error_kind?: string[]+ max_attempts?: number+ max_count?: number+ invocation_ids?: string[]+}++export interface RerunRequest {+ filter: RerunFilter+}++/**+ * Max window the user may pass — matches the ClickHouse TTL on+ * `hog_invocation_results`. Older rows are already gone via part drop.+ */+export const RERUN_MAX_WINDOW_DAYS = 30++export interface RerunCursor {+ scheduled_at: string+ invocation_id: string+}++export interface RerunJobProgress {+ queued: number+ skipped: number+ /** Keyset cursor on (scheduled_at, invocation_id). Undefined on first page; null when exhausted. */+ cursor?: RerunCursor | null+ /** True once the worker has processed every page or exhausted max_count. */+ done: boolean+ /** Last error from a page; non-fatal — the next reschedule retries. */+ last_error?: string+ /**+ * Number of pages that have committed progress to this job. Bumped per+ * call to `processPage`. Surfaces on the wrapper lifecycle row as `attempts`+ * so the Invocations UI can show "this re-run has worked X pages so far".+ */+ pages_processed?: number+}++export interface RerunJobState {+ function_kind: RerunFunctionKind+ function_id: string+ request: RerunRequest+ progress: RerunJobProgress+}++/** Hard cap on rows fetched per rerun page (also caps a by-IDs request slice). */+export const RERUN_PAGE_SIZE = 200diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.tsnew file mode 100644index 000000000000..69e2329ae2f3--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts@@ -0,0 +1,627 @@+import { MockKafkaProducerWrapper } from '~/tests/helpers/mocks/producer.mock'++import { ClickHouseClient } from '@clickhouse/client'+import { DateTime } from 'luxon'++import { createCdpConsumerDeps } from '~/tests/helpers/cdp'+import { Clickhouse } from '~/tests/helpers/clickhouse'+import { waitForExpect } from '~/tests/helpers/expectations'+import { ensureKafkaTopics, resetKafka } from '~/tests/helpers/kafka'+import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'++import { KAFKA_HOG_INVOCATION_RESULTS } from '../../config/kafka-topics'+import { KafkaProducerWrapper } from '../../kafka/producer'+import { Hub, Team } from '../../types'+import { closeHub, createHub } from '../../utils/db/hub'+import { UUIDT } from '../../utils/utils'+import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'+import { createCdpOutputsRegistry } from '../outputs/registry'+import { HogInputsService } from '../services/hog-inputs.service'+import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'+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 { RerunPaginatorService } from './rerun-paginator.service'++const ActualKafkaProducerWrapper = jest.requireActual('../../kafka/producer').KafkaProducerWrapper++/**+ * Integration test for RerunPaginatorService.+ *+ * Instead of mocking the ClickHouse client, this test seeds real lifecycle rows+ * through `HogInvocationResultsService.queueLifecycleRow` → Kafka → ClickHouse+ * Kafka MV → `hog_invocation_results`, then runs the paginator against the real+ * data. Only the side effects the paginator emits (the running lifecycle row ++ * the cyclotron re-enqueue) are mocked, so we can assert what got produced.+ *+ * This proves the whole pipeline end-to-end: the queueLifecycleRow shape that+ * the worker uses, the Kafka MV's JSON parsing, and the paginator's argMax+ * collapse query all line up.+ */+describe('RerunPaginatorService integration', () => {+ jest.setTimeout(60_000)++ let hub: Hub+ let kafkaProducer: KafkaProducerWrapper+ let team: Team+ let clickhouse: Clickhouse+ let hogFunction: HogFunctionType+ let seedingService: HogInvocationResultsService+ let chClient: ClickHouseClient+ let paginator: RerunPaginatorService+ let cyclotronJobQueue: jest.Mocked<CyclotronJobQueue>+ let paginatorLifecycleService: jest.Mocked<HogInvocationResultsService>+ let paginatorMonitoringService: jest.Mocked<HogFunctionMonitoringService>+ let hogFunctionManager: HogFunctionManagerService+ let hogFlowManager: jest.Mocked<HogFlowManagerService>+ let hogInputsService: jest.Mocked<HogInputsService>++ beforeAll(() => {+ clickhouse = Clickhouse.create()+ chClient = Clickhouse.createClient()+ })++ afterAll(async () => {+ clickhouse?.close()+ await chClient?.close()+ })++ let seededCount = 0+ /**+ * Seed `n` lifecycle rows for the given function. Each entry becomes a real+ * Kafka produce + MV ingestion, so by the time this returns ClickHouse has+ * the rows ready for the paginator to read.+ */+ const seedRows = async (+ rows: Array<{+ invocation_id: string+ status: 'running' | 'succeeded' | 'failed'+ error?: Error+ scheduledAt?: Date+ }>+ ): Promise<void> => {+ for (const r of rows) {+ const globals = createHogExecutionGlobals({+ project: { id: team.id } as any,+ event: {+ uuid: `evt-${r.invocation_id}`,+ event: '$pageview',+ properties: {},+ timestamp: '2026-05-10T09:00:00Z',+ } as any,+ })+ const invocation: CyclotronJobInvocationHogFunction = {+ id: r.invocation_id,+ state: {+ globals: globals as any,+ timings: [],+ attempts: 0,+ },+ teamId: team.id,+ functionId: hogFunction.id,+ hogFunction,+ queue: 'hog',+ queuePriority: 0,+ queueScheduledAt: r.scheduledAt ? ({ toJSDate: () => r.scheduledAt } as any) : undefined,+ }+ seedingService.queueLifecycleRow(invocation, r.status, { error: r.error })+ }+ await seedingService.flush()++ // Track cumulative seeded rows so calling seedRows twice in the same+ // test waits for *all* rows (rather than trivially passing on the+ // previous seed's count).+ seededCount += rows.length+ const expected = seededCount++ await waitForExpect(async () => {+ const got = await clickhouse.query<{ c: number }>(+ `SELECT count() AS c FROM hog_invocation_results+ WHERE team_id = ${team.id}+ AND function_id = '${hogFunction.id}'`+ )+ expect(Number(got[0]?.c ?? 0)).toBeGreaterThanOrEqual(expected)+ }, 30_000)+ }++ beforeAll(async () => {+ MockKafkaProducerWrapper.create = jest.fn((...args: any[]) => ActualKafkaProducerWrapper.create(...args))+ await resetKafka()+ await ensureKafkaTopics([KAFKA_HOG_INVOCATION_RESULTS])+ await clickhouse.truncate('hog_invocation_results_data')+ })++ beforeEach(async () => {+ await resetTestDatabase()+ await clickhouse.truncate('hog_invocation_results_data')+ seededCount = 0++ hub = await createHub()+ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ team = await getFirstTeam(hub.postgres)++ // Real seeding path: outputs → kafka → MV → CH.+ const deps = createCdpConsumerDeps(hub, kafkaProducer)+ const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, {+ ...hub,+ HOG_INVOCATION_RESULTS_TOPIC: KAFKA_HOG_INVOCATION_RESULTS,+ } as any)+ seedingService = new HogInvocationResultsService(outputs, { HOG_INVOCATION_RESULTS_ENABLED: true })++ hogFunction = await _insertHogFunction(hub.postgres, team.id, {+ type: 'destination',+ hog: 'print("hi")',+ bytecode: [],+ inputs_schema: [],+ inputs: {},+ })++ // Real hog function manager so rehydrate can resolve the function from postgres.+ hogFunctionManager = new HogFunctionManagerService(hub.postgres, hub.pubSub, hub.encryptedFields)+ hogFunctionManager['onHogFunctionsReloaded'](team.id, [hogFunction.id])++ // Hog flow manager and inputs service stay mocked — this suite focuses on the+ // hog-function path and the CH query/rehydrate logic. Hog flow rehydration is+ // exercised structurally (rest of the same code path) but not end-to-end here.+ hogFlowManager = {+ getHogFlow: jest.fn().mockResolvedValue(null),+ } as unknown as jest.Mocked<HogFlowManagerService>++ hogInputsService = {+ buildInputsWithGlobals: jest+ .fn()+ .mockImplementation((_fn, globals) => Promise.resolve({ ...globals, inputs: { resolved: true } })),+ } as unknown as jest.Mocked<HogInputsService>++ cyclotronJobQueue = {+ queueInvocations: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<CyclotronJobQueue>++ // The paginator's lifecycle service is mocked so we can assert what it+ // got asked to write (the 'running' row for each rerun). The actual+ // CH state for that running row is a flaky-on-Redpanda concern handled+ // in the e2e test — here we only care that the paginator queues it.+ paginatorLifecycleService = {+ queueLifecycleRow: jest.fn(),+ queueRerunWrapperRow: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ dropQueuedRowsFor: jest.fn(),+ } as unknown as jest.Mocked<HogInvocationResultsService>++ paginatorMonitoringService = {+ queueLogs: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<HogFunctionMonitoringService>++ paginator = new RerunPaginatorService(+ chClient,+ hogFunctionManager,+ hogFlowManager,+ hogInputsService,+ paginatorLifecycleService,+ cyclotronJobQueue,+ paginatorMonitoringService,+ 10000+ )+ })++ afterEach(async () => {+ await kafkaProducer?.disconnect().catch(() => undefined)+ await closeHub(hub)+ })++ const buildState = (overrides: Partial<RerunJobState> = {}): RerunJobState => ({+ function_kind: 'hog_function',+ function_id: hogFunction.id,+ // Window is required by the unified rerun schema. Default to a wide+ // year-long window so the seeded test data falls inside.+ request: { filter: { window_start: '2026-01-01T00:00:00Z', window_end: '2027-01-01T00:00:00Z' } },+ progress: { queued: 0, skipped: 0, done: false },+ ...overrides,+ })++ describe('by-ids mode', () => {+ it('rehydrates and re-enqueues only the requested invocations, ignoring others', async () => {+ await seedRows([+ { invocation_id: 'inv-a', status: 'failed', error: new Error('http_5xx error') },+ { invocation_id: 'inv-b', status: 'succeeded' },+ { invocation_id: 'inv-c', status: 'failed', error: new Error('timeout') },+ ])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-a', 'inv-c'],+ },+ },+ })++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })++ expect(cyclotronJobQueue.queueInvocations).toHaveBeenCalledTimes(1)+ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const enqueuedIds = enqueued.map((i) => i.id).sort()+ expect(enqueuedIds).toEqual(['inv-a', 'inv-c'])++ // Each rerun invocation gets a 'running' lifecycle row queued.+ // is_retry / attempts are derived inside queueLifecycleRow from+ // state.rerunAttempts (set by the rehydrator), not passed as an opt.+ const runningCalls = paginatorLifecycleService.queueLifecycleRow.mock.calls.filter(+ (c) => c[1] === 'running'+ )+ expect(runningCalls).toHaveLength(2)+ // Each queued invocation's state should carry rerunAttempts=1.+ for (const [invocation] of runningCalls) {+ expect((invocation as CyclotronJobInvocationHogFunction).state.rerunAttempts).toBe(1)+ }++ expect(next.progress.queued).toBe(2)+ expect(next.progress.skipped).toBe(0)+ expect(next.progress.done).toBe(true)+ })++ it('skips invocation ids that have no matching row in clickhouse', async () => {+ await seedRows([{ invocation_id: 'inv-real', status: 'failed', error: new Error('5xx') }])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-real', 'inv-missing'],+ },+ },+ })++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })++ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ expect(enqueued.map((i) => i.id)).toEqual(['inv-real'])+ // by-ids mode marks done once remaining_ids is drained, regardless of+ // whether every id had a matching CH row.+ expect(next.progress.done).toBe(true)+ })++ it('rebuilds inputs via HogInputsService rather than trusting the stored payload', async () => {+ await seedRows([{ invocation_id: 'inv-rebuild', status: 'failed', error: new Error('boom') }])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-rebuild'],+ },+ },+ })++ await paginator.processPage(team.id, state, { jobId: 'test-rerun-job', createdAt: DateTime.now() })++ expect(hogInputsService.buildInputsWithGlobals).toHaveBeenCalledTimes(1)+ const [fn, persistedGlobals] = hogInputsService.buildInputsWithGlobals.mock.calls[0]+ expect(fn.id).toBe(hogFunction.id)+ // The persisted globals were stripped of `inputs` before storage.+ expect(persistedGlobals).not.toHaveProperty('inputs')++ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ expect((enqueued[0].state.globals as any).inputs).toEqual({ resolved: true })+ })+ })++ describe('by-filter mode', () => {+ it('defaults to status=failed and only matches failed rows in the window', async () => {+ await seedRows([+ { invocation_id: 'ok-1', status: 'succeeded' },+ { invocation_id: 'fail-1', status: 'failed', error: new Error('500 err') },+ { invocation_id: 'fail-2', status: 'failed', error: new Error('timeout') },+ ])++ 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(),+ })++ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ const ids = enqueued.map((i) => i.id).sort()+ expect(ids).toEqual(['fail-1', 'fail-2'])+ expect(next.progress.queued).toBe(2)+ })++ it('honours error_kind filter (only http_5xx rows are rerun)', async () => {+ await seedRows([+ { invocation_id: 'inv-500', status: 'failed', error: new Error('500 server error') },+ { invocation_id: 'inv-timeout', status: 'failed', error: new Error('Request timed out') },+ ])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ error_kind: ['http_5xx'],+ },+ },+ })++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })+ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0]?.[0] as+ | CyclotronJobInvocationHogFunction[]+ | undefined+ expect(enqueued?.map((i) => i.id)).toEqual(['inv-500'])+ expect(next.progress.queued).toBe(1)+ })++ it('honours max_count by capping queued+skipped at the user-provided limit', async () => {+ await seedRows([+ { invocation_id: 'a', status: 'failed', error: new Error('5xx') },+ { invocation_id: 'b', status: 'failed', error: new Error('5xx') },+ { invocation_id: 'c', status: 'failed', error: new Error('5xx') },+ ])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ max_count: 2,+ },+ },+ })++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })+ expect(next.progress.queued).toBe(2)+ expect(next.progress.done).toBe(true)+ })++ it('returns done=true with an empty page when no rows match the filter', async () => {+ await seedRows([{ invocation_id: 'inv-ok', status: 'succeeded' }])++ 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.queued).toBe(0)+ expect(next.progress.done).toBe(true)+ expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()+ })+ })++ describe('rehydration', () => {+ it('skips rows whose hog function has been deleted between original run and rerun', async () => {+ const orphanedFn = await _insertHogFunction(hub.postgres, team.id, {+ type: 'destination',+ hog: 'print("orphan")',+ bytecode: [],+ })+ // Seed under the orphaned function...+ const prevFn = hogFunction+ hogFunction = orphanedFn+ await seedRows([{ invocation_id: 'inv-orphan', status: 'failed', error: new Error('5xx') }])+ hogFunction = prevFn++ // ...then ask the paginator to rerun it. The paginator's hog function+ // manager (real) lazy-loads the orphaned function (still exists in PG)+ // — we explicitly stub `getHogFunction` to return null to simulate the+ // "deleted between original run and rerun" scenario.+ const realGetHogFunction = hogFunctionManager.getHogFunction.bind(hogFunctionManager)+ jest.spyOn(hogFunctionManager, 'getHogFunction').mockImplementation(async (id) => {+ if (id === orphanedFn.id) {+ return null+ }+ return realGetHogFunction(id)+ })++ const state: RerunJobState = {+ function_kind: 'hog_function',+ function_id: orphanedFn.id,+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-orphan'],+ },+ },+ progress: { queued: 0, skipped: 0, done: false },+ }++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })+ expect(next.progress.queued).toBe(0)+ expect(next.progress.skipped).toBe(1)+ expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()+ })+ })++ describe('conflict handling', () => {+ it('counts in-flight invocations as skipped instead of failing the page', async () => {+ await seedRows([{ invocation_id: 'inv-conflict', status: 'failed', error: new Error('5xx') }])++ // Simulate the v2 queue raising a conflict for our re-enqueue —+ // we want the paginator to log + count it as a skip, not blow up+ // the page. Use the same re-export the paginator imports from so+ // `instanceof` matches.+ const { CyclotronJobConflictError } = await import('../services/cyclotron-v2/index.js')+ cyclotronJobQueue.queueInvocations.mockRejectedValueOnce(new CyclotronJobConflictError('inv-conflict'))++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['inv-conflict'],+ },+ },+ })++ const { state: next } = await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })+ expect(next.progress.queued).toBe(0)+ expect(next.progress.skipped).toBe(1)+ expect(next.progress.done).toBe(true)+ expect(next.progress.last_error).toBeUndefined()+ })+ })++ 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 brokenChClient = {+ query: jest.fn().mockRejectedValue(new Error('clickhouse boom')),+ } as unknown as ClickHouseClient+ const brokenPaginator = new RerunPaginatorService(+ brokenChClient,+ hogFunctionManager,+ hogFlowManager,+ hogInputsService,+ paginatorLifecycleService,+ cyclotronJobQueue,+ paginatorMonitoringService,+ 10000+ )++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: ['x'],+ },+ },+ progress: { queued: 0, skipped: 0, done: false },+ })++ const { state: next } = await brokenPaginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })+ expect(next.progress.done).toBe(false)+ expect(next.progress.last_error).toContain('clickhouse boom')+ expect(cyclotronJobQueue.queueInvocations).not.toHaveBeenCalled()+ })+ })++ describe('done logic (real CH)', () => {+ it('marks done when fewer rows came back than the page size (no further pages)', async () => {+ await seedRows([{ invocation_id: 'one', status: 'failed', error: new Error('5xx') }])++ 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(),+ })+ // 1 row < RERUN_PAGE_SIZE → done.+ expect(next.progress.done).toBe(true)+ // Sanity: RERUN_PAGE_SIZE constant didn't regress to a tiny value.+ expect(RERUN_PAGE_SIZE).toBeGreaterThan(10)+ })++ it('carries first_scheduled_at from the stored row onto the rehydrated invocation state', async () => {+ // The producer writes `first_scheduled_at` verbatim on every retry's+ // lifecycle row so ReplacingMergeTree doesn't collapse it away. The+ // paginator's contract here: read it from the stored row, stamp it+ // onto the rehydrated state so the next retry's producer sees the+ // same original time. Without this, every kafka retry would+ // overwrite first_scheduled_at with the latest scheduled_at.+ const id = 'inv-first-' + new UUIDT().toString()+ const originalScheduledAt = new Date('2026-05-01T09:00:00Z')+ await seedRows([+ {+ invocation_id: id,+ status: 'failed',+ error: new Error('5xx'),+ scheduledAt: originalScheduledAt,+ },+ ])++ const state = buildState({+ request: {+ filter: {+ window_start: '2026-01-01T00:00:00Z',+ window_end: '2027-01-01T00:00:00Z',+ invocation_ids: [id],+ },+ },+ })++ await paginator.processPage(team.id, state, {+ jobId: 'test-rerun-job',+ createdAt: DateTime.now(),+ })++ const enqueued = cyclotronJobQueue.queueInvocations.mock.calls[0][0] as CyclotronJobInvocationHogFunction[]+ expect(enqueued).toHaveLength(1)+ // CH returns DateTime64 as 'YYYY-MM-DD HH:MM:SS.ffffff' — just check+ // the date portion matches the original scheduled time. The exact+ // serialization differs between paths but the day/time is preserved.+ expect(enqueued[0].state.firstScheduledAt).toMatch(/^2026-05-01[T ]09:00:00/)+ })++ it('reads the latest row per invocation via argMax(_, version) collapse', async () => {+ // Same invocation_id, multiple lifecycle rows simulating: original+ // failed → user clicked rerun → rerun running → rerun succeeded.+ // The paginator should see the LATEST `succeeded` state, not the+ // earlier `failed`. (Filter mode defaults to status=failed, so an+ // invocation that's now succeeded should NOT be picked up.)+ const id = 'inv-collapse-' + new UUIDT().toString()+ await seedRows([{ invocation_id: id, status: 'failed', error: new Error('5xx') }])+ // Small sleep to ensure version monotonicity is observable.+ await new Promise((r) => setTimeout(r, 5))+ await seedRows([{ invocation_id: id, status: 'succeeded' }])++ 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.queued).toBe(0)+ })+ })++ // Silence unused-import noise for HogFunctionInvocationGlobals which is+ // referenced indirectly via the rehydration assertion.+ void (undefined as unknown as HogFunctionInvocationGlobals)+})diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.tsnew file mode 100644index 000000000000..64498ee93a3d--- /dev/null+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts@@ -0,0 +1,557 @@+import { ClickHouseClient } from '@clickhouse/client'+import { DateTime } from 'luxon'+import { Counter } from 'prom-client'++import { parseJSON } from '../../utils/json-parse'+import { logger } from '../../utils/logger'+import { CyclotronJobConflictError } from '../services/cyclotron-v2'+import { HogInputsService } from '../services/hog-inputs.service'+import { createHogFlowInvocation } from '../services/hogflows/hogflow-executor.service'+import { HogFlowManagerService } from '../services/hogflows/hogflow-manager.service'+import { CyclotronJobQueue } from '../services/job-queue/job-queue'+import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'+import { HogFunctionMonitoringService } from '../services/monitoring/hog-function-monitoring.service'+import { HogInvocationResultsService } from '../services/monitoring/hog-invocation-results.service'+import {+ CyclotronJobInvocation,+ CyclotronJobInvocationHogFlow,+ CyclotronJobInvocationHogFunction,+ HogFunctionFilterGlobals,+ HogFunctionInvocationGlobals,+} from '../types'+import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'+import { RERUN_PAGE_SIZE, RerunFunctionKind, RerunJobProgress, RerunJobState } from './rerun-job.types'++const counterRerunPageProcessed = new Counter({+ name: 'cdp_hog_invocation_rerun_pages_processed_total',+ help: 'Rerun paginator pages processed, by function kind and outcome.',+ labelNames: ['function_kind', 'outcome'],+})++const counterRerunInvocationsQueued = new Counter({+ name: 'cdp_hog_invocation_rerun_queued_total',+ help: 'Reruned invocations queued onto cyclotron, by function kind.',+ labelNames: ['function_kind'],+})++const counterRerunInvocationsSkipped = new Counter({+ name: 'cdp_hog_invocation_rerun_skipped_total',+ help: 'Invocations matched by rerun filters but skipped (over max_attempts, missing function, malformed payload).',+ labelNames: ['function_kind', 'reason'],+})++// ClickHouse's `DateTime64` parser only accepts 'YYYY-MM-DD HH:MM:SS[.fff]'.+// The Django serializer (and our internal `scheduled_at` column representation)+// uses ISO 8601 with `T` and `Z`. Convert before binding to query params.+const toClickhouseDateTime = (value: string): string => {+ if (!value) {+ return value+ }+ // Already in CH form? Leave it alone.+ if (!value.includes('T')) {+ return value+ }+ return value+ .replace('T', ' ')+ .replace(/Z$/, '')+ .replace(/([+-]\d{2}):?(\d{2})$/, '')+}++interface InvocationRow {+ invocation_id: string+ parent_run_id: string+ attempts: number+ last_scheduled_at: string+ first_scheduled_at: string+ invocation_globals: string+}++export interface PageOutcome {+ /** New job state after this page. The worker writes it back via reschedule(state) — or ack()s if done. */+ state: RerunJobState+}++/**+ * Context the worker passes alongside the parsed state on each page. Lets the+ * paginator stamp wrapper lifecycle rows with the right `invocation_id`+ * (= cyclotron job id) and a stable `scheduled_at` for the wrapper across pages.+ */+export interface RerunJobContext {+ jobId: string+ /** When the wrapper job was first created in cyclotron — anchor for the wrapper's `scheduled_at`. */+ createdAt: DateTime+}++/**+ * Processes a single page of work for a rerun wrapper job. Pure-ish — the+ * caller (the worker) handles the cyclotron-v2 ack/reschedule flow with the+ * returned state. Splitting the page-of-work logic out of the worker keeps+ * the cyclotron plumbing testable in isolation from the ClickHouse paging.+ */+export class RerunPaginatorService {+ constructor(+ private clickhouse: ClickHouseClient,+ private hogFunctionManager: HogFunctionManagerService,+ private hogFlowManager: HogFlowManagerService,+ private hogInputsService: HogInputsService,+ private invocationResultsRowsService: HogInvocationResultsService,+ private cyclotronJobQueue: CyclotronJobQueue,+ private monitoringService: HogFunctionMonitoringService,+ // Mirror of the Django serializer cap (HOG_INVOCATION_RERUN_MAX_COUNT env var).+ private maxCount: number+ ) {}++ /**+ * Run one page of work for the given rerun job state. Returns the new+ * state. `state.progress.done = true` means the worker should `ack()` the+ * wrapper job; otherwise it should `reschedule({ state })` to continue.+ */+ async processPage(teamId: number, state: RerunJobState, context: RerunJobContext): Promise<PageOutcome> {+ const { function_kind, function_id, progress } = state++ try {+ const rows = await this.fetchPage(teamId, state)++ // Stop early if the user's max_count or our hard server cap is reached.+ const remainingBudget = this.remainingBudget(state)+ const toProcess = rows.slice(0, remainingBudget)++ const { queued, skipped, queuedInvocations } = await this.rehydrateBatch(teamId, state, toProcess)++ let conflictSkipped = 0+ if (queuedInvocations.length > 0) {+ // Rerun re-uses the original invocation_id. Routing is the+ // same as cdp-events-consumer (`getTarget()` per invocation —+ // hog → kafka, hog_flow → postgres-v2). `overwriteExisting`+ // only matters for the v2 path: it upserts ONLY when the+ // existing cyclotron row is in a terminal state. If a v2-+ // routed invocation's row is still active, the v2 manager+ // raises CyclotronJobConflictError listing the conflicting+ // ids — skip those, still queue the rest. Kafka-routed+ // invocations can't conflict (no PK) and v1 is unsupported+ // for rerun (throws at the queue boundary).+ let invocationsToEnqueue = queuedInvocations+ try {+ await this.cyclotronJobQueue.queueInvocations(invocationsToEnqueue, {+ overwriteExisting: true,+ })+ } catch (e) {+ if (!(e instanceof CyclotronJobConflictError)) {+ throw e+ }+ const raw = e.conflictingIds+ const conflictingIds = new Set(Array.isArray(raw) ? raw : [raw])+ logger.warn('Rerun skipping invocations that are still in-flight', {+ rerun_function_kind: function_kind,+ rerun_function_id: function_id,+ conflicting_invocation_ids: Array.from(conflictingIds),+ })+ conflictSkipped = conflictingIds.size+ for (let i = 0; i < conflictSkipped; i++) {+ counterRerunInvocationsSkipped.labels(function_kind, 'still_in_flight').inc()+ }+ // The conflicting invocations also queued a 'running'+ // lifecycle row above — drop them so we don't show a stale+ // running row for an invocation that didn't actually+ // re-enqueue.+ invocationsToEnqueue = queuedInvocations.filter((i) => !conflictingIds.has(i.id))+ this.invocationResultsRowsService.dropQueuedRowsFor(Array.from(conflictingIds))+ }+ await this.invocationResultsRowsService.flush()+ counterRerunInvocationsQueued.labels(function_kind).inc(invocationsToEnqueue.length)++ // One debug log per re-enqueued invocation, keyed on its own+ // `instance_id` so the line shows up on that invocation's+ // expanded log panel — not on the wrapper's. Makes it obvious+ // why the run shows up twice when scanning a function's logs.+ const now = DateTime.now()+ this.monitoringService.queueLogs(+ invocationsToEnqueue.map((inv) => ({+ team_id: teamId,+ log_source: function_kind,+ log_source_id: function_id,+ instance_id: inv.id,+ timestamp: now,+ level: 'debug',+ message: `Re-queued by re-run job ${context.jobId}.`,+ })),+ function_kind+ )+ }++ const nextProgress: RerunJobProgress = {+ queued: progress.queued + queued - conflictSkipped,+ skipped: progress.skipped + skipped + conflictSkipped,+ cursor: this.advanceCursor(state, toProcess),+ done: this.isDone(state, rows.length, toProcess.length),+ last_error: undefined,+ pages_processed: (progress.pages_processed ?? 0) + 1,+ }++ counterRerunPageProcessed.labels(function_kind, rows.length === 0 ? 'empty' : 'ok').inc()++ // 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)++ return { state: { ...state, progress: nextProgress } }+ } catch (err) {+ const errMessage = err instanceof Error ? err.message : String(err)+ logger.error('Rerun paginator page failed', {+ rerun_function_kind: function_kind,+ rerun_function_id: function_id,+ 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 }+ await this.writeWrapperUpdate(teamId, state, context, errorProgress, err)+ return { state: { ...state, progress: errorProgress } }+ }+ }++ /**+ * Write a wrapper lifecycle row + log line reflecting the result of one+ * page. Status is `'running'` for in-flight pages, `'succeeded'` /+ * `'failed'` for the final page. Errors flow into the lifecycle row's+ * `error_kind` / `error_message` for failed terminal writes only — a+ * recoverable per-page error gets logged but the row stays `running` so+ * the worker can reschedule and try again.+ *+ * Public so the worker can write a terminal `failed` row from its catch+ * handler when the whole wrapper is being given up on.+ */+ async writeWrapperUpdate(+ teamId: number,+ state: RerunJobState,+ context: RerunJobContext,+ nextProgress: RerunJobProgress,+ pageError: unknown | undefined+ ): Promise<void> {+ const status: 'running' | 'succeeded' | 'failed' = nextProgress.done ? 'succeeded' : 'running'+ const now = new Date()+ this.invocationResultsRowsService.queueRerunWrapperRow({+ teamId,+ parentFunctionKind: state.function_kind,+ functionId: state.function_id,+ rerunJobId: context.jobId,+ status,+ pagesProcessed: nextProgress.pages_processed ?? 0,+ filter: state.request.filter,+ scheduledAt: context.createdAt.toJSDate(),+ startedAt: context.createdAt.toJSDate(),+ finishedAt: status !== 'running' ? now : undefined,+ error: pageError,+ })++ const pageErrorMessage = pageError ? (pageError instanceof Error ? pageError.message : String(pageError)) : null+ const message = nextProgress.done+ ? `Re-run finished. queued=${nextProgress.queued} skipped=${nextProgress.skipped}`+ : pageErrorMessage+ ? `Re-run page failed: ${pageErrorMessage}. Worker will retry.`+ : `Re-run page done. queued=${nextProgress.queued} skipped=${nextProgress.skipped} cursor=${+ nextProgress.cursor+ ? `${nextProgress.cursor.scheduled_at}/${nextProgress.cursor.invocation_id}`+ : 'end'+ }`++ this.monitoringService.queueLogs(+ [+ {+ team_id: teamId,+ log_source: state.function_kind,+ log_source_id: state.function_id,+ instance_id: context.jobId,+ timestamp: DateTime.fromJSDate(now),+ level: pageErrorMessage ? 'warn' : nextProgress.done ? 'info' : 'info',+ message,+ },+ ],+ state.function_kind+ )++ await Promise.all([this.invocationResultsRowsService.flush(), this.monitoringService.flush()])+ }++ /**+ * Write the terminal `failed` wrapper lifecycle row from the worker's+ * unrecoverable catch path. Logs the cause and flushes so the failure is+ * visible immediately on the Invocations tab.+ */+ async writeWrapperFailure(+ teamId: number,+ state: RerunJobState,+ context: RerunJobContext,+ error: unknown+ ): Promise<void> {+ const errMessage = error instanceof Error ? error.message : String(error)+ const now = new Date()+ this.invocationResultsRowsService.queueRerunWrapperRow({+ teamId,+ parentFunctionKind: state.function_kind,+ functionId: state.function_id,+ rerunJobId: context.jobId,+ status: 'failed',+ pagesProcessed: state.progress.pages_processed ?? 0,+ filter: state.request.filter,+ scheduledAt: context.createdAt.toJSDate(),+ startedAt: context.createdAt.toJSDate(),+ finishedAt: now,+ error,+ })++ this.monitoringService.queueLogs(+ [+ {+ team_id: teamId,+ log_source: state.function_kind,+ log_source_id: state.function_id,+ instance_id: context.jobId,+ timestamp: DateTime.fromJSDate(now),+ level: 'error',+ message: `Re-run aborted: ${errMessage}`,+ },+ ],+ state.function_kind+ )++ await Promise.all([this.invocationResultsRowsService.flush(), this.monitoringService.flush()])+ }++ private remainingBudget(state: RerunJobState): number {+ const cap = Math.min(state.request.filter.max_count ?? this.maxCount, this.maxCount)+ return Math.max(0, cap - state.progress.queued - state.progress.skipped)+ }++ private isDone(state: RerunJobState, fetchedCount: number, processedCount: number): boolean {+ const budgetSpent = this.remainingBudget(state) <= processedCount+ const pageWasPartial = fetchedCount < RERUN_PAGE_SIZE+ return budgetSpent || pageWasPartial+ }++ private advanceCursor(state: RerunJobState, processed: InvocationRow[]): RerunJobState['progress']['cursor'] {+ if (processed.length === 0) {+ return null+ }+ const last = processed[processed.length - 1]+ return { scheduled_at: last.last_scheduled_at, invocation_id: last.invocation_id }+ }++ private async fetchPage(teamId: number, state: RerunJobState): Promise<InvocationRow[]> {+ const filter = state.request.filter+ const requestedStatus = filter.status?.length ? filter.status : ['failed']+ // The Django serializer accepts ISO 8601 ('2026-05-01T00:00:00Z'), but+ // ClickHouse `DateTime64` only parses 'YYYY-MM-DD HH:MM:SS[.fff]'. Convert+ // before passing as a query parameter.+ const windowStart = toClickhouseDateTime(filter.window_start)+ const windowEnd = toClickhouseDateTime(filter.window_end)+ const cursorScheduledAt = state.progress.cursor?.scheduled_at+ ? toClickhouseDateTime(state.progress.cursor.scheduled_at)+ : ''++ // Keyset pagination on (scheduled_at, invocation_id). When the cursor+ // is undefined we start from the top of the window. ClickHouse needs+ // the tuple compared via a single AND-chained inequality.+ const cursor = state.progress.cursor+ const cursorClause =+ cursor && cursor.scheduled_at+ ? ' AND (scheduled_at, invocation_id) < ({cursor_scheduled_at:DateTime64}, {cursor_invocation_id:String})'+ : ''+ const errorKindClause = filter.error_kind?.length+ ? 'AND argMax(error_kind, version) IN {error_kind:Array(String)}'+ : ''+ const maxAttemptsClause =+ filter.max_attempts !== undefined ? 'AND argMax(attempts, version) < {max_attempts:UInt8}' : ''+ // `invocation_ids` is an OPTIONAL additional restriction layered on top+ // of the time window. The window is still required — it pins the query+ // to a small set of date partitions instead of scanning everything.+ const invocationIdsClause = filter.invocation_ids?.length+ ? 'AND invocation_id IN {invocation_ids:Array(String)}'+ : ''++ const result = await this.clickhouse.query({+ query: `/* team_id:${teamId} query_type:hog_invocation_rerun_page */+ SELECT+ invocation_id,+ argMax(parent_run_id, version) AS parent_run_id,+ argMax(attempts, version) AS attempts,+ argMax(invocation_globals, version) AS invocation_globals,+ argMax(first_scheduled_at, version) AS first_scheduled_at,+ max(scheduled_at) AS last_scheduled_at+ FROM hog_invocation_results+ WHERE team_id = {team_id:Int64}+ AND function_kind = {function_kind:String}+ AND function_id = {function_id:String}+ AND scheduled_at >= {window_start:DateTime64}+ AND scheduled_at < {window_end:DateTime64}+ ${invocationIdsClause}+ ${cursorClause}+ GROUP BY invocation_id+ HAVING argMax(is_deleted, version) = 0+ AND argMax(status, version) IN {status:Array(String)}+ ${errorKindClause}+ ${maxAttemptsClause}+ ORDER BY last_scheduled_at DESC, invocation_id DESC+ LIMIT {limit:UInt32}`,+ query_params: {+ team_id: teamId,+ function_kind: state.function_kind,+ function_id: state.function_id,+ window_start: windowStart,+ window_end: windowEnd,+ status: requestedStatus,+ error_kind: filter.error_kind ?? [],+ max_attempts: filter.max_attempts ?? 255,+ invocation_ids: filter.invocation_ids ?? [],+ cursor_scheduled_at: cursorScheduledAt,+ cursor_invocation_id: cursor?.invocation_id ?? '',+ limit: RERUN_PAGE_SIZE,+ },+ format: 'JSONEachRow',+ })++ return (await result.json()) as InvocationRow[]+ }++ private async rehydrateBatch(+ teamId: number,+ state: RerunJobState,+ rows: InvocationRow[]+ ): Promise<{ queued: number; skipped: number; queuedInvocations: CyclotronJobInvocation[] }> {+ const maxAttempts = state.request.filter.max_attempts+ const queuedInvocations: CyclotronJobInvocation[] = []+ let skipped = 0++ for (const row of rows) {+ if (maxAttempts !== undefined && row.attempts >= maxAttempts) {+ counterRerunInvocationsSkipped.labels(state.function_kind, 'over_max_attempts').inc()+ skipped+++ continue+ }+ try {+ const invocation = await this.rehydrateInvocation(teamId, state.function_kind, state.function_id, row)+ if (!invocation) {+ counterRerunInvocationsSkipped.labels(state.function_kind, 'rehydrate_failed').inc()+ skipped+++ continue+ }+ // Rerun-start lifecycle row. is_retry/attempts are derived from+ // `state.rerunAttempts` (set by rehydrateInvocation above). The+ // matching terminal row is written by the worker when the+ // invocation finishes — same derivation, same is_retry=1.+ this.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ queuedInvocations.push(invocation)+ } catch (e) {+ logger.error('Rerun failed to rehydrate invocation', {+ error: e instanceof Error ? e.message : String(e),+ invocation_id: row.invocation_id,+ })+ counterRerunInvocationsSkipped.labels(state.function_kind, 'exception').inc()+ skipped+++ }+ }++ return { queued: queuedInvocations.length, skipped, queuedInvocations }+ }++ private async rehydrateInvocation(+ teamId: number,+ functionKind: RerunFunctionKind,+ functionId: string,+ row: InvocationRow+ ): Promise<CyclotronJobInvocation | null> {+ let parsedGlobals: unknown+ try {+ parsedGlobals = parseJSON(row.invocation_globals)+ } catch {+ return null+ }++ if (functionKind === 'hog_function') {+ const hogFunction = await this.hogFunctionManager.getHogFunction(functionId)+ if (!hogFunction || hogFunction.team_id !== teamId) {+ return null+ }+ // The persisted globals have `inputs` stripped — secrets stay out+ // of ClickHouse. Re-resolve inputs here from the current hog function+ // config + integration store, which also gives the rerun run any+ // input changes the user made since the original invocation.+ const persistedGlobals = parsedGlobals as HogFunctionInvocationGlobals+ const globalsWithInputs = await this.hogInputsService.buildInputsWithGlobals(hogFunction, persistedGlobals)+ const invocation: CyclotronJobInvocationHogFunction = {+ // Preserve invocation_id so lifecycle rows collapse under the+ // ReplacingMergeTree on the same key.+ id: row.invocation_id,+ state: {+ globals: globalsWithInputs,+ timings: [],+ // `attempts` is the fetch-retry counter and is reset to 0+ // for the rerun run. `rerunAttempts` (read from the+ // stored row's `attempts` column, which holds the prior+ // rerun count) drives `is_retry` and `attempts` on the+ // lifecycle rows.+ attempts: 0,+ rerunAttempts: (row.attempts || 0) + 1,+ // Carry the original first-scheduled time forward — the+ // producer writes this verbatim on every retry's lifecycle+ // rows so ReplacingMergeTree doesn't collapse it away.+ firstScheduledAt: row.first_scheduled_at,+ },+ teamId,+ functionId,+ parentRunId: row.parent_run_id || null,+ hogFunction,+ queue: 'hog',+ queuePriority: 0,+ }+ return invocation+ }++ if (functionKind === 'hog_flow') {+ const hogFlow = await this.hogFlowManager.getHogFlow(functionId)+ if (!hogFlow || hogFlow.team_id !== teamId) {+ return null+ }+ const persistedState = parsedGlobals as Record<string, any>+ const eventForFilter = persistedState.event ?? {}+ const filterGlobals: HogFunctionFilterGlobals = convertToHogFunctionFilterGlobal({+ event: eventForFilter,+ person: undefined,+ groups: {},+ variables: persistedState.variables ?? {},+ } as any)++ const invocation: CyclotronJobInvocationHogFlow = createHogFlowInvocation(+ {+ project: { id: teamId, name: '', url: '' },+ event: eventForFilter,+ person: undefined,+ groups: {},+ variables: persistedState.variables ?? {},+ source: { name: '', url: '' },+ } as any,+ hogFlow,+ filterGlobals+ )+ invocation.id = row.invocation_id+ invocation.parentRunId = row.parent_run_id || null+ invocation.state = {+ ...invocation.state!,+ event: eventForFilter,+ actionStepCount: persistedState.actionStepCount ?? 0,+ variables: persistedState.variables ?? {},+ // Sticky rerun counter — mirror the hog function path so the+ // lifecycle row producer can derive `attempts` / `is_retry`+ // for flows too, and the `max_attempts` guard actually trips.+ rerunAttempts: (row.attempts || 0) + 1,+ firstScheduledAt: row.first_scheduled_at,+ }+ return invocation+ }++ return null+ }+}diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex c3e26eb21c75..68ed9025366b 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -282,6 +282,162 @@ describe('Cyclotron V2', () => {expect(rows[0].person_id).toBe(validPersonId)expect(rows[1].person_id).toBe('group-key-not-a-uuid')})++ describe('overwriteExisting (rerun re-enqueue)', () => {+ it('createJob with overwriteExisting=true refuses to clobber an in-flight (running) row', async () => {+ const id = uuidv7()+ await manager.createJob({ id, teamId: 1, queueName: QUEUE })+ // Dequeue → row is now 'running'.+ const worker = createWorker()+ const jobs = await dequeueOneBatch(worker)+ expect(jobs).toHaveLength(1)+ expect((await queryJob(id)).status).toBe('running')++ const { CyclotronJobConflictError } = await import('./manager.js')+ await expect(+ manager.createJob({+ id,+ teamId: 1,+ queueName: QUEUE,+ overwriteExisting: true,+ })+ ).rejects.toBeInstanceOf(CyclotronJobConflictError)++ // Existing row's status untouched.+ expect((await queryJob(id)).status).toBe('running')+ })++ it('createJob with overwriteExisting=true refuses to clobber an available (queued, not yet dequeued) row', async () => {+ const id = uuidv7()+ await manager.createJob({ id, teamId: 1, queueName: QUEUE })+ expect((await queryJob(id)).status).toBe('available')++ const { CyclotronJobConflictError } = await import('./manager.js')+ await expect(+ manager.createJob({ id, teamId: 1, queueName: QUEUE, overwriteExisting: true })+ ).rejects.toBeInstanceOf(CyclotronJobConflictError)+ })++ it('createJob with overwriteExisting=true resets an existing terminal row to available', async () => {+ const id = uuidv7()+ // First insert + drive to terminal state via the worker.+ await manager.createJob({ id, teamId: 1, queueName: QUEUE, state: Buffer.from('v1') })+ const worker = createWorker()+ const jobs = await dequeueOneBatch(worker)+ await jobs[0].ack()+ expect((await queryJob(id)).status).toBe('completed')++ // Re-create with the same id and overwriteExisting=true — this+ // is the rerun path. The row should flip back to 'available'+ // with the new state.+ await manager.createJob({+ id,+ teamId: 1,+ queueName: QUEUE,+ state: Buffer.from('v2'),+ overwriteExisting: true,+ })+ const row = await queryJob(id)+ expect(row.status).toBe('available')+ expect(row.state).toEqual(Buffer.from('v2'))+ expect(row.lock_id).toBeNull()+ expect(row.last_heartbeat).toBeNull()+ // transition_count bumps so the janitor's poison-pill guard+ // still has signal across reruns.+ expect(row.transition_count).toBeGreaterThan(0)+ })++ it('createJob with overwriteExisting=true on a never-seen id behaves like a normal insert', async () => {+ const id = uuidv7()+ await manager.createJob({+ id,+ teamId: 1,+ queueName: QUEUE,+ state: Buffer.from('fresh'),+ overwriteExisting: true,+ })+ const row = await queryJob(id)+ expect(row.status).toBe('available')+ expect(row.state).toEqual(Buffer.from('fresh'))+ })++ it('bulkCreateJobs with overwriteExisting reports skipped ids via CyclotronJobConflictError when some are still active', async () => {+ const terminalId = uuidv7()+ const activeId = uuidv7()+ // Drive terminalId to completed, leave activeId in 'available'.+ await manager.bulkCreateJobs([+ { id: terminalId, teamId: 1, queueName: QUEUE },+ { id: activeId, teamId: 1, queueName: QUEUE },+ ])+ const worker = createWorker()+ const dequeued = await dequeueOneBatch(worker)+ const completedJob = dequeued.find((j) => j.id === terminalId)!+ await completedJob.ack()+ // The other one will still be 'running' at this point — reschedule it+ // back to 'available' so the test mirrors a more common case.+ const activeJob = dequeued.find((j) => j.id === activeId)!+ await activeJob.reschedule()+ expect((await queryJob(activeId)).status).toBe('available')++ const { CyclotronJobConflictError } = await import('./manager.js')+ await expect(+ manager.bulkCreateJobs([+ {+ id: terminalId,+ teamId: 1,+ queueName: QUEUE,+ overwriteExisting: true,+ state: Buffer.from('reset'),+ },+ {+ id: activeId,+ teamId: 1,+ queueName: QUEUE,+ overwriteExisting: true,+ state: Buffer.from('would-clobber'),+ },+ ])+ ).rejects.toBeInstanceOf(CyclotronJobConflictError)++ // The terminal one was still upserted; the active one was not.+ expect((await queryJob(terminalId)).state).toEqual(Buffer.from('reset'))+ expect((await queryJob(activeId)).state).toBeNull()+ })++ it('bulkCreateJobs with overwriteExisting flag upserts every row in the batch', async () => {+ const ids = [uuidv7(), uuidv7()]+ // Seed both as completed.+ await manager.bulkCreateJobs(ids.map((id) => ({ id, teamId: 1, queueName: QUEUE })))+ const worker = createWorker()+ const dequeued = await dequeueOneBatch(worker)+ await Promise.all(dequeued.map((j) => j.ack()))++ // Re-create both via bulk upsert.+ const resultIds = await manager.bulkCreateJobs(+ ids.map((id) => ({+ id,+ teamId: 1,+ queueName: QUEUE,+ state: Buffer.from('rerun'),+ overwriteExisting: true,+ }))+ )+ expect(resultIds).toEqual(ids)+ for (const id of ids) {+ const row = await queryJob(id)+ expect(row.status).toBe('available')+ expect(row.state).toEqual(Buffer.from('rerun'))+ }+ })++ it('without overwriteExisting, re-creating with the same id throws on the PK conflict', async () => {+ const id = uuidv7()+ await manager.createJob({ id, teamId: 1, queueName: QUEUE })+ await expect(manager.createJob({ id, teamId: 1, queueName: QUEUE })).rejects.toThrow(+ /duplicate key value/i+ )+ })+ })})// ── Worker ───────────────────────────────────────────────────────diff --git a/nodejs/src/cdp/services/cyclotron-v2/index.ts b/nodejs/src/cdp/services/cyclotron-v2/index.tsindex 7abffd084ad9..7ad53231dee0 100644--- a/nodejs/src/cdp/services/cyclotron-v2/index.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/index.ts@@ -1,4 +1,4 @@-export { CyclotronV2Manager } from './manager'+export { CyclotronV2Manager, CyclotronJobConflictError } from './manager'export { CyclotronV2Worker } from './worker'export { CyclotronV2Janitor } from './janitor'export { CyclotronV2JanitorService } from './janitor-service'diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.tsindex 994bed710239..5f8d1f7aae0c 100644--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts@@ -4,6 +4,24 @@ import { v7 as uuidv7 } from 'uuid'import { logger } from '../../../utils/logger'import { CyclotronV2JobInit, CyclotronV2JobInitSchema, CyclotronV2ManagerConfig } from './types'+/**+ * Thrown when an `overwriteExisting` createJob / bulkCreateJobs hits a row+ * that's still in an active state ('available' or 'running'). Callers should+ * treat this as a "skip and warn" rather than a hard failure — the user is+ * trying to rerun an invocation that's still mid-flight, which the safer+ * default is to refuse.+ */+export class CyclotronJobConflictError extends Error {+ constructor(public readonly conflictingIds: string | string[]) {+ super(+ `Cyclotron job overwrite refused: existing row(s) ${+ Array.isArray(conflictingIds) ? conflictingIds.join(', ') : conflictingIds+ } are in an active state`+ )+ this.name = 'CyclotronJobConflictError'+ }+}+export class CyclotronV2Manager {private pool: Poolprivate readonly depthLimit: number@@ -32,14 +50,40 @@ export class CyclotronV2Manager {const id = job.id ?? uuidv7()const now = new Date()- await this.pool.query(+ // Rerun re-uses the original invocation_id so lifecycle rows collapse+ // under the same ReplacingMergeTree key. The ON CONFLICT clause resets+ // a prior _terminal_ job row back to 'available' with fresh state. If+ // the existing row is still active ('available' or 'running'), the+ // UPDATE's WHERE fails, the row isn't returned, and we surface that as+ // a skip so the caller can warn rather than silently clobber in-flight+ // work. `transition_count` bumps so the janitor's poison-pill guard+ // still applies across reruns.+ const upsertClause = job.overwriteExisting+ ? `ON CONFLICT (id) DO UPDATE SET+ status = 'available',+ priority = EXCLUDED.priority,+ scheduled = EXCLUDED.scheduled,+ lock_id = NULL,+ last_heartbeat = NULL,+ last_transition = EXCLUDED.last_transition,+ transition_count = cyclotron_jobs.transition_count + 1,+ parent_run_id = EXCLUDED.parent_run_id,+ state = EXCLUDED.state,+ distinct_id = EXCLUDED.distinct_id,+ person_id = EXCLUDED.person_id,+ action_id = EXCLUDED.action_id+ WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')+ RETURNING id`+ : 'RETURNING id'+ const result = await this.pool.query<{ id: string }>(`INSERT INTO cyclotron_jobs(id, team_id, function_id, queue_name, status, priority, scheduled, created,lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,parent_run_id, state, distinct_id, person_id, action_id)VALUES ($1, $2, $3, $4, 'available', $5, $6, $7,NULL, NULL, 0, 0, $7,- $8, $9, $10, $11, $12)`,+ $8, $9, $10, $11, $12)+ ${upsertClause}`,[id,job.teamId,@@ -55,15 +99,29 @@ export class CyclotronV2Manager {job.actionId ?? null,])+ if (job.overwriteExisting && result.rows.length === 0) {+ // Existing row was in an active state — refuse to clobber.+ throw new CyclotronJobConflictError(id)+ }return id}+ /**+ * Bulk-insert jobs. If any input is flagged `overwriteExisting`, the entire+ * batch uses `ON CONFLICT (id) DO UPDATE` so existing rows are reset back+ * to 'available' rather than colliding on the primary key. This is how the+ * rerun path re-enqueues an invocation while preserving its+ * `invocation_id` (so lifecycle rows collapse under one ReplacingMergeTree+ * key). Mixing overwrite + non-overwrite in the same batch isn't supported+ * — pre-split into separate calls if you need that.+ */async bulkCreateJobs(inputs: CyclotronV2JobInit[]): Promise<string[]> {if (inputs.length === 0) {return []}const jobs = inputs.map((input) => CyclotronV2JobInitSchema.parse(input))+ const overwriteExisting = jobs.some((j) => j.overwriteExisting)await this.insertGuard()@@ -96,7 +154,24 @@ export class CyclotronV2Manager {actionIds.push(job.actionId ?? null)}- await this.pool.query(+ const upsertClause = overwriteExisting+ ? `ON CONFLICT (id) DO UPDATE SET+ status = 'available',+ priority = EXCLUDED.priority,+ scheduled = EXCLUDED.scheduled,+ lock_id = NULL,+ last_heartbeat = NULL,+ last_transition = EXCLUDED.last_transition,+ transition_count = cyclotron_jobs.transition_count + 1,+ parent_run_id = EXCLUDED.parent_run_id,+ state = EXCLUDED.state,+ distinct_id = EXCLUDED.distinct_id,+ person_id = EXCLUDED.person_id,+ action_id = EXCLUDED.action_id+ WHERE cyclotron_jobs.status IN ('completed', 'failed', 'canceled')+ RETURNING id`+ : 'RETURNING id'+ const result = await this.pool.query<{ id: string }>(`INSERT INTO cyclotron_jobs(id, team_id, function_id, queue_name, status, priority, scheduled, created,lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,@@ -119,7 +194,8 @@ export class CyclotronV2Manager {unnest($8::bytea[]),unnest($9::text[]),unnest($10::text[]),- unnest($11::text[])`,+ unnest($11::text[])+ ${upsertClause}`,[ids,teamIds,@@ -136,6 +212,14 @@ export class CyclotronV2Manager {])+ if (overwriteExisting) {+ const returnedIds = new Set(result.rows.map((r) => r.id))+ const skipped = ids.filter((id) => !returnedIds.has(id))+ if (skipped.length > 0) {+ throw new CyclotronJobConflictError(skipped)+ }+ }+return ids}diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.tsindex 10e5f92fcd71..14e315d35eeb 100644--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts@@ -21,6 +21,12 @@ export const CyclotronV2JobInitSchema = z.object({distinctId: z.string().nullish(),personId: z.string().nullish(),actionId: z.string().nullish(),+ // When `true`, the insert uses ON CONFLICT (id) DO UPDATE — the existing+ // row's status is reset to 'available', the lock is cleared, and state is+ // replaced. Used by the rerun path so a re-execution can reuse the+ // original `invocation_id` (so lifecycle rows collapse under one+ // ReplacingMergeTree key) without colliding on the cyclotron_jobs PK.+ overwriteExisting: z.boolean().optional(),})export type CyclotronV2JobInit = z.infer<typeof CyclotronV2JobInitSchema>diff --git a/nodejs/src/cdp/services/invocation-results.service.test.ts b/nodejs/src/cdp/services/invocation-results.service.test.tsindex 8455de18b1ec..53d327a16e32 100644--- a/nodejs/src/cdp/services/invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/invocation-results.service.test.ts@@ -2,10 +2,12 @@ import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'import { InvocationResultsService } from './invocation-results.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogInvocationResultsService } from './monitoring/hog-invocation-results.service'import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service'describe('InvocationResultsService', () => {let monitoringService: jest.Mocked<HogFunctionMonitoringService>+ let invocationResultsRowsService: jest.Mocked<HogInvocationResultsService>let warehouseWebhooksService: jest.Mocked<WarehouseWebhooksService>let capturedEventsService: jest.Mocked<CapturedEventsService>let service: InvocationResultsService@@ -21,6 +23,11 @@ describe('InvocationResultsService', () => {flush: jest.fn().mockResolvedValue(undefined),} as unknown as jest.Mocked<HogFunctionMonitoringService>+ invocationResultsRowsService = {+ queueInvocationResults: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<HogInvocationResultsService>+warehouseWebhooksService = {queueInvocationResults: jest.fn(),flush: jest.fn().mockResolvedValue(undefined),@@ -31,15 +38,22 @@ describe('InvocationResultsService', () => {flush: jest.fn().mockResolvedValue(undefined),} as unknown as jest.Mocked<CapturedEventsService>- service = new InvocationResultsService(monitoringService, warehouseWebhooksService, capturedEventsService)+ service = new InvocationResultsService(+ monitoringService,+ invocationResultsRowsService,+ warehouseWebhooksService,+ capturedEventsService+ )})describe('queueInvocationResults', () => {- it('fans the same results out to all three sub-services', async () => {+ it('fans the same results out to all sub-services', async () => {await service.queueInvocationResults(results)expect(monitoringService.queueInvocationResults).toHaveBeenCalledTimes(1)expect(monitoringService.queueInvocationResults).toHaveBeenCalledWith(results)+ expect(invocationResultsRowsService.queueInvocationResults).toHaveBeenCalledTimes(1)+ expect(invocationResultsRowsService.queueInvocationResults).toHaveBeenCalledWith(results)expect(warehouseWebhooksService.queueInvocationResults).toHaveBeenCalledTimes(1)expect(warehouseWebhooksService.queueInvocationResults).toHaveBeenCalledWith(results)expect(capturedEventsService.queueInvocationResults).toHaveBeenCalledTimes(1)@@ -74,15 +88,16 @@ describe('InvocationResultsService', () => {})describe('flush', () => {- it('flushes all three sub-services', async () => {+ it('flushes all sub-services', async () => {await service.flush()expect(monitoringService.flush).toHaveBeenCalledTimes(1)+ expect(invocationResultsRowsService.flush).toHaveBeenCalledTimes(1)expect(warehouseWebhooksService.flush).toHaveBeenCalledTimes(1)expect(capturedEventsService.flush).toHaveBeenCalledTimes(1)})- it('flushes all three in parallel (all start before any finish)', async () => {+ it('flushes all in parallel (all start before any finish)', async () => {const order: string[] = []const trackOrder = (name: string) =>jest.fn().mockImplementation(() => {@@ -93,19 +108,22 @@ describe('InvocationResultsService', () => {})monitoringService.flush = trackOrder('monitoring')+ invocationResultsRowsService.flush = trackOrder('invocationResults')warehouseWebhooksService.flush = trackOrder('warehouse')capturedEventsService.flush = trackOrder('captured')await service.flush()- // All three should have started before any of them finish — proves Promise.all parallelism.+ // All should have started before any of them finish — proves Promise.all parallelism.const lastStart = Math.max(order.indexOf('monitoring:start'),+ order.indexOf('invocationResults:start'),order.indexOf('warehouse:start'),order.indexOf('captured:start'))const firstEnd = Math.min(order.indexOf('monitoring:end'),+ order.indexOf('invocationResults:end'),order.indexOf('warehouse:end'),order.indexOf('captured:end'))@@ -114,11 +132,14 @@ describe('InvocationResultsService', () => {})describe('queueInvocationResultsAndFlush', () => {- it('queues across all three then flushes all three', async () => {+ it('queues across all sub-services then flushes all of them', async () => {const callOrder: string[] = []monitoringService.queueInvocationResults = jest.fn().mockImplementation(() => {callOrder.push('monitoring.queue')})+ invocationResultsRowsService.queueInvocationResults = jest.fn().mockImplementation(() => {+ callOrder.push('invocationResults.queue')+ })warehouseWebhooksService.queueInvocationResults = jest.fn().mockImplementation(() => {callOrder.push('warehouse.queue')})@@ -130,6 +151,10 @@ describe('InvocationResultsService', () => {callOrder.push('monitoring.flush')return Promise.resolve()})+ invocationResultsRowsService.flush = jest.fn().mockImplementation(() => {+ callOrder.push('invocationResults.flush')+ return Promise.resolve()+ })warehouseWebhooksService.flush = jest.fn().mockImplementation(() => {callOrder.push('warehouse.flush')return Promise.resolve()@@ -141,14 +166,16 @@ describe('InvocationResultsService', () => {await service.queueInvocationResultsAndFlush(results)- // All three queue calls must complete before any flush call starts.+ // All queue calls must complete before any flush call starts.const lastQueueIdx = Math.max(callOrder.indexOf('monitoring.queue'),+ callOrder.indexOf('invocationResults.queue'),callOrder.indexOf('warehouse.queue'),callOrder.indexOf('captured.queue'))const firstFlushIdx = Math.min(callOrder.indexOf('monitoring.flush'),+ callOrder.indexOf('invocationResults.flush'),callOrder.indexOf('warehouse.flush'),callOrder.indexOf('captured.flush'))@@ -159,6 +186,7 @@ describe('InvocationResultsService', () => {describe('exposed sub-services', () => {it('exposes the underlying services as public readonly fields', () => {expect(service.monitoringService).toBe(monitoringService)+ expect(service.invocationResultsRowsService).toBe(invocationResultsRowsService)expect(service.warehouseWebhooksService).toBe(warehouseWebhooksService)expect(service.capturedEventsService).toBe(capturedEventsService)})diff --git a/nodejs/src/cdp/services/invocation-results.service.ts b/nodejs/src/cdp/services/invocation-results.service.tsindex 5610f6d4bafd..2592a945d1ed 100644--- a/nodejs/src/cdp/services/invocation-results.service.ts+++ b/nodejs/src/cdp/services/invocation-results.service.ts@@ -3,18 +3,21 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'+import { HogInvocationResultsService } from './monitoring/hog-invocation-results.service'import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service'/**- * Fans `CyclotronJobInvocationResult` batches out to the three sinks every+ * Fans `CyclotronJobInvocationResult` batches out to the sinks every* CDP consumer/API caller needs:*- * - `HogFunctionMonitoringService` — app metrics + log entries+ * - `HogFunctionMonitoringService` — aggregated app metrics + log entries+ * - `HogInvocationResultsService` — per-invocation lifecycle row in ClickHouse+ * (powers the new runs UI + rerun path)* - `WarehouseWebhooksService` — warehouse source webhook payloads* - `CapturedEventsService` — PostHog events emitted via posthog.capture()** Callers interact with this one service instead of coordinating queue/flush- * calls across the three individually. `queueInvocationResultsAndFlush` is the+ * calls across the four individually. `queueInvocationResultsAndFlush` is the* common path — `queueInvocationResults` + `flush` are exposed for the rare* cases that split the two (e.g. source webhooks, which queue inline and flush* asynchronously after the HTTP response).@@ -22,6 +25,7 @@ import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.serviceexport class InvocationResultsService {constructor(public readonly monitoringService: HogFunctionMonitoringService,+ public readonly invocationResultsRowsService: HogInvocationResultsService,public readonly warehouseWebhooksService: WarehouseWebhooksService,public readonly capturedEventsService: CapturedEventsService) {}@@ -29,6 +33,7 @@ export class InvocationResultsService {queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void> {return instrumentFn(`cdpConsumer.handleEachBatch.produceResults`, async () => {this.monitoringService.queueInvocationResults(results)+ this.invocationResultsRowsService.queueInvocationResults(results)this.warehouseWebhooksService.queueInvocationResults(results)await this.capturedEventsService.queueInvocationResults(results)})@@ -37,6 +42,7 @@ export class InvocationResultsService {async flush(): Promise<void> {await Promise.all([this.monitoringService.flush(),+ this.invocationResultsRowsService.flush(),this.warehouseWebhooksService.flush(),this.capturedEventsService.flush(),])diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.tsindex 3bd694f28aec..f4618c3e1af1 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts@@ -107,7 +107,10 @@ export class CyclotronJobQueuePostgresV2 {return new HealthCheckResultError('CyclotronV2Worker is not healthy', {})}- public async queueInvocations(invocations: CyclotronJobInvocation[]): Promise<void> {+ public async queueInvocations(+ invocations: CyclotronJobInvocation[],+ options: { overwriteExisting?: boolean } = {}+ ): Promise<void> {if (invocations.length === 0) {return}@@ -116,7 +119,10 @@ export class CyclotronJobQueuePostgresV2 {throw new Error('CyclotronV2Manager not initialized')}- const jobs = invocations.map((inv) => invocationToV2JobInit(inv))+ const jobs = invocations.map((inv) => ({+ ...invocationToV2JobInit(inv),+ overwriteExisting: options.overwriteExisting,+ }))try {const chunked = chunk(jobs, this.config.CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE)diff --git a/nodejs/src/cdp/services/job-queue/job-queue.test.ts b/nodejs/src/cdp/services/job-queue/job-queue.test.tsindex 0727ae4cb698..90fb98299683 100644--- a/nodejs/src/cdp/services/job-queue/job-queue.test.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue.test.ts@@ -153,9 +153,10 @@ describe('CyclotronJobQueue', () => {)await queue.queueInvocations([invocation])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([- expect.objectContaining({ teamId: 79155, queue: 'hog' }),- ])+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(+ [expect.objectContaining({ teamId: 79155, queue: 'hog' })],+ { overwriteExisting: undefined }+ )expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([])})@@ -167,7 +168,9 @@ describe('CyclotronJobQueue', () => {)await queue.queueInvocations([invocation])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([])+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {+ overwriteExisting: undefined,+ })expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ teamId: 79155, queue: 'hog' }),])@@ -183,7 +186,9 @@ describe('CyclotronJobQueue', () => {expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ teamId: 79155, queue: 'hogflow' }),])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([])+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {+ overwriteExisting: undefined,+ })})it('should not affect other teams', async () => {@@ -197,7 +202,9 @@ describe('CyclotronJobQueue', () => {expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([expect.objectContaining({ teamId: 1, queue: 'hog' }),])- expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([])+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], {+ overwriteExisting: undefined,+ })})})@@ -364,6 +371,137 @@ describe('CyclotronJobQueue', () => {})})++ describe('rerun routing (overwriteExisting)', () => {+ const buildQueueWithMocks = (mapping: string): CyclotronJobQueue => {+ config.CYCLOTRON_NODE_DATABASE_URL = 'postgres://localhost:5432'+ config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = mapping+ const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ queue['jobQueuePostgres'].queueInvocations = jest.fn()+ queue['jobQueueKafka'].queueInvocations = jest.fn()+ queue['jobQueuePostgresV2'] = {+ startAsProducer: jest.fn(),+ queueInvocations: jest.fn(),+ } as any+ return queue+ }++ const hogInvocation = () => createInvocation({ ...createHogExecutionGlobals(), inputs: {} }, exampleHogFunction)+ const hogflowInvocation = () => ({ ...hogInvocation(), queue: 'hogflow' as const })++ it('routes hog → kafka under the standard mapping (no overwrite passed through)', async () => {+ const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')+ const inv = hogInvocation()++ await queue.queueInvocations([inv], { overwriteExisting: true })++ expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([+ expect.objectContaining({ queue: 'hog' }),+ ])+ // The v2 producer is only called with the v2-routed slice, which here is empty.+ // `overwriteExisting` is irrelevant when nothing routes there.+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith([], { overwriteExisting: true })+ })++ it('preserves the invocation_id through the kafka rerun path', async () => {+ const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')+ const inv = hogInvocation()+ const originalId = inv.id++ await queue.queueInvocations([inv], { overwriteExisting: true })++ // The rerun paginator sets `id: row.invocation_id` on the rehydrated+ // invocation; this asserts the routing path doesn't generate a new+ // UUID before producing to kafka, so lifecycle rows for the rerun+ // run collapse onto the same key in CH.+ const enqueued = (queue['jobQueueKafka'].queueInvocations as jest.Mock).mock.calls[0][0]+ expect(enqueued).toHaveLength(1)+ expect(enqueued[0].id).toBe(originalId)+ })++ it('preserves the invocation_id through the postgres-v2 rerun path', async () => {+ const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')+ const inv = hogflowInvocation()+ const originalId = inv.id++ await queue.queueInvocations([inv], { overwriteExisting: true })++ const enqueued = (queue['jobQueuePostgresV2']!.queueInvocations as jest.Mock).mock.calls[0][0]+ expect(enqueued).toHaveLength(1)+ expect(enqueued[0].id).toBe(originalId)+ })++ it('routes hogflow → postgres-v2 with overwriteExisting forwarded', async () => {+ const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')+ const inv = hogflowInvocation()++ await queue.queueInvocations([inv], { overwriteExisting: true })++ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(+ [expect.objectContaining({ queue: 'hogflow' })],+ { overwriteExisting: true }+ )+ expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([])+ })++ it('splits mixed batches across kafka + v2 under per-queue routing', async () => {+ const queue = buildQueueWithMocks('*:kafka,hogflow:postgres-v2')++ await queue.queueInvocations([hogInvocation(), hogflowInvocation(), hogInvocation()], {+ overwriteExisting: true,+ })++ expect(queue['jobQueueKafka'].queueInvocations).toHaveBeenCalledWith([+ expect.objectContaining({ queue: 'hog' }),+ expect.objectContaining({ queue: 'hog' }),+ ])+ expect(queue['jobQueuePostgresV2']!.queueInvocations).toHaveBeenCalledWith(+ [expect.objectContaining({ queue: 'hogflow' })],+ { overwriteExisting: true }+ )+ expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([])+ })++ it('throws for invocations routed to postgres-v1 under overwriteExisting', async () => {+ const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')+ const inv = hogInvocation()++ await expect(queue.queueInvocations([inv], { overwriteExisting: true })).rejects.toThrow(+ /Rerun routing to postgres-v1 is unsupported \(queue=hog\)/+ )+ })++ it('still throws on v1 even when only one of N invocations targets v1', async () => {+ const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')++ await expect(+ queue.queueInvocations([hogflowInvocation(), hogInvocation()], { overwriteExisting: true })+ ).rejects.toThrow(/postgres-v1 is unsupported/)+ })++ it('allows v1 routing when overwriteExisting is NOT set (normal traffic path)', async () => {+ const queue = buildQueueWithMocks('*:kafka,hog:postgres,hogflow:postgres-v2')+ const inv = hogInvocation()++ await expect(queue.queueInvocations([inv])).resolves.toBeUndefined()+ expect(queue['jobQueuePostgres'].queueInvocations).toHaveBeenCalledWith([+ expect.objectContaining({ queue: 'hog' }),+ ])+ })++ it('throws if anything is routed to postgres-v2 but v2 was never constructed', async () => {+ // No CYCLOTRON_NODE_DATABASE_URL → v2 stays unconstructed.+ config.CYCLOTRON_NODE_DATABASE_URL = undefined+ config.CDP_CYCLOTRON_JOB_QUEUE_PRODUCER_MAPPING = '*:kafka'+ const queue = new CyclotronJobQueue(config.CONSUMER_BATCH_SIZE, config.KAFKA_CLIENT_RACK, config)+ queue['jobQueuePostgres'].queueInvocations = jest.fn()+ queue['jobQueueKafka'].queueInvocations = jest.fn()+ // Force a v2-targeted invocation by patching the router.+ jest.spyOn(queue as any, 'getTarget').mockReturnValue('postgres-v2' as CyclotronJobQueueSource)++ await expect(queue.queueInvocations([hogInvocation()])).rejects.toThrow(/cyclotron-v2 is not configured/)+ })+ })})describe('getProducerMapping', () => {diff --git a/nodejs/src/cdp/services/job-queue/job-queue.ts b/nodejs/src/cdp/services/job-queue/job-queue.tsindex f384f31f7677..1cd2637eb692 100644--- a/nodejs/src/cdp/services/job-queue/job-queue.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue.ts@@ -144,8 +144,15 @@ export class CyclotronJobQueue {await this.jobQueuePostgres.startAsProducer()}- if (targets.has('postgres-v2')) {- await this.jobQueuePostgresV2?.startAsProducer()+ // Always start v2 when it's been constructed (which only happens when+ // CYCLOTRON_NODE_DATABASE_URL is set). The routing mapping isn't the+ // only path that reaches v2 — `queueInvocations({ overwriteExisting:+ // true })` routes through v2 unconditionally for the rerun flow, so a+ // service whose routing mapping doesn't reference v2 (the rerun+ // worker, for instance) would still hit a 'CyclotronV2Manager not+ // initialized' throw at first rerun if we gated on the mapping alone.+ if (this.jobQueuePostgresV2) {+ await this.jobQueuePostgresV2.startAsProducer()}if (targets.has('kafka')) {@@ -246,10 +253,14 @@ export class CyclotronJobQueue {return target}- public async queueInvocations(invocations: CyclotronJobInvocation[]) {+ public async queueInvocations(+ invocations: CyclotronJobInvocation[],+ options: { overwriteExisting?: boolean } = {}+ ) {const sanitized = invocations.map((inv) =>sanitizeInvocationForPersistence(inv, { stripPerson: this.stripPersonMatcher(inv.teamId) }))+const postgresInvocations: CyclotronJobInvocation[] = []const postgresV2Invocations: CyclotronJobInvocation[] = []const kafkaInvocations: CyclotronJobInvocation[] = []@@ -257,7 +268,18 @@ export class CyclotronJobQueue {for (const invocation of sanitized) {const target = this.getTarget(invocation)+ // Reruns carry `overwriteExisting: true` so a re-enqueue of an+ // `invocation_id` that already has a cyclotron row doesn't fail+ // on the PK. v2 supports it via ON CONFLICT, kafka doesn't need+ // it (no PK at all), v1 has neither — so v1 + overwrite is an+ // error rather than a silent fall-through.if (target === 'postgres') {+ if (options.overwriteExisting) {+ throw new Error(+ `Rerun routing to postgres-v1 is unsupported (queue=${invocation.queue}). ` ++ `Route hog workloads to kafka and hog_flow workloads to postgres-v2.`+ )+ }postgresInvocations.push(invocation)} else if (target === 'postgres-v2') {postgresV2Invocations.push(invocation)@@ -266,6 +288,10 @@ export class CyclotronJobQueue {}}+ if (postgresV2Invocations.length > 0 && !this.jobQueuePostgresV2) {+ throw new Error(`Invocations routed to postgres-v2 but cyclotron-v2 is not configured`)+ }+await Promise.all([instrumentFn({@@ -280,9 +306,15 @@ export class CyclotronJobQueue {{key: 'cyclotron.queue_invocations.postgres_v2',sendException: false,- getLoggingContext: () => ({ count: postgresV2Invocations.length }),+ getLoggingContext: () => ({+ count: postgresV2Invocations.length,+ overwriteExisting: !!options.overwriteExisting,+ }),},- () => this.jobQueuePostgresV2!.queueInvocations(postgresV2Invocations)+ () =>+ this.jobQueuePostgresV2!.queueInvocations(postgresV2Invocations, {+ overwriteExisting: options.overwriteExisting,+ })): Promise.resolve(),instrumentFn(diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.tsnew file mode 100644index 000000000000..b4b29b211a36--- /dev/null+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts@@ -0,0 +1,257 @@+import { DateTime } from 'luxon'++import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'++import { parseJSON } from '../../../utils/json-parse'+import { createExampleInvocation } from '../../_tests/fixtures'+import { CdpOutput } from '../../cdp-services'+import { HogInvocationResultRow, HogInvocationResultsService } from './hog-invocation-results.service'++const buildOutputsMock = (): jest.Mocked<IngestionOutputs<CdpOutput>> => {+ return {+ produce: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<IngestionOutputs<CdpOutput>>+}++const parseProducedRows = (outputs: jest.Mocked<IngestionOutputs<CdpOutput>>): HogInvocationResultRow[] => {+ return outputs.produce.mock.calls.map((call) => {+ const arg = call[1] as { key: Buffer | null; value: Buffer | null }+ return parseJSON(arg.value!.toString('utf8')) as HogInvocationResultRow+ })+}++describe('HogInvocationResultsService', () => {+ let outputs: jest.Mocked<IngestionOutputs<CdpOutput>>+ let service: HogInvocationResultsService++ beforeEach(() => {+ outputs = buildOutputsMock()+ service = new HogInvocationResultsService(outputs, { HOG_INVOCATION_RESULTS_ENABLED: true })+ })++ describe('feature flag', () => {+ it('produces nothing when HOG_INVOCATION_RESULTS_ENABLED is false', async () => {+ service = new HogInvocationResultsService(outputs, { HOG_INVOCATION_RESULTS_ENABLED: false })++ const invocation = createExampleInvocation()+ service.queueLifecycleRow(invocation, 'running')+ service.queueInvocationResults([+ {+ invocation,+ finished: true,+ error: undefined,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ } as any,+ ])++ await service.flush()+ expect(outputs.produce).not.toHaveBeenCalled()+ })+ })++ describe('queueLifecycleRow', () => {+ it('writes a status=running row with start timing and no error fields', async () => {+ const invocation = createExampleInvocation()+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(1)+ const row = rows[0]+ expect(row.status).toBe('running')+ expect(row.function_kind).toBe('hog_function')+ expect(row.team_id).toBe(invocation.teamId)+ expect(row.function_id).toBe(invocation.functionId)+ expect(row.invocation_id).toBe(invocation.id)+ expect(row.is_retry).toBe(0)+ expect(row.started_at).not.toBeNull()+ expect(row.finished_at).toBeNull()+ expect(row.error_kind).toBe('')+ expect(row.error_message).toBe('')+ })++ it('strips inputs from invocation_globals — secrets must not be persisted', async () => {+ const invocation = createExampleInvocation(+ { id: 'fn-1', team_id: 1 },+ {+ inputs: {+ api_key: 'sk-super-secret',+ nested: { token: 'abc123' },+ } as any,+ }+ )+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(1)+ const globals = parseJSON(rows[0].invocation_globals) as Record<string, any>++ // The event/person/project context we care about is preserved.+ expect(globals.event?.uuid).toBeDefined()+ expect(globals.person?.id).toBeDefined()+ // But `inputs` is gone entirely.+ expect(globals).not.toHaveProperty('inputs')+ // And the serialized blob does not mention the secret anywhere+ // (catches the case where a future schema change moves inputs+ // under a different key without us noticing).+ expect(rows[0].invocation_globals).not.toContain('sk-super-secret')+ expect(rows[0].invocation_globals).not.toContain('abc123')+ })++ it('marks is_retry=1 and attempts=N when state.rerunAttempts is set', async () => {+ const invocation = createExampleInvocation()+ invocation.state.rerunAttempts = 1+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows[0].is_retry).toBe(1)+ expect(rows[0].attempts).toBe(1)+ })++ it('leaves is_retry=0 and attempts=0 when state.rerunAttempts is unset (original run)', async () => {+ const invocation = createExampleInvocation()+ // Fetch-retry counter is bumped by the executor — it must NOT bleed+ // into the lifecycle row's `attempts`/`is_retry` fields.+ invocation.state.attempts = 3+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows[0].is_retry).toBe(0)+ expect(rows[0].attempts).toBe(0)+ })++ it('extracts event_uuid, distinct_id, and person_id into promoted columns', async () => {+ const invocation = createExampleInvocation({}, {+ event: {+ uuid: 'event-uuid-123',+ event: 'test',+ elements_chain: '',+ distinct_id: 'distinct-456',+ url: 'http://localhost',+ properties: {},+ timestamp: '2026-05-01T00:00:00Z',+ },+ person: {+ id: 'person-789',+ name: 'x',+ url: 'http://localhost',+ properties: {},+ },+ } as any)+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows[0].event_uuid).toBe('event-uuid-123')+ expect(rows[0].distinct_id).toBe('distinct-456')+ expect(rows[0].person_id).toBe('person-789')+ })+ })++ describe('queueInvocationResults', () => {+ it('writes status=succeeded on a result with no error', async () => {+ const invocation = createExampleInvocation()+ service.queueInvocationResults([+ {+ invocation,+ finished: true,+ error: undefined,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ } as any,+ ])+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(1)+ expect(rows[0].status).toBe('succeeded')+ expect(rows[0].error_kind).toBe('')+ })++ it('writes status=failed and classifies the error kind', async () => {+ const invocation = createExampleInvocation()+ service.queueInvocationResults([+ {+ invocation,+ finished: true,+ error: new Error('Request timed out after 30s'),+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ } as any,+ ])+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(1)+ expect(rows[0].status).toBe('failed')+ expect(rows[0].error_kind).toBe('timeout')+ expect(rows[0].error_message).toContain('timed out')+ })++ it('produces no row for an in-flight result that has not finished and has no error', async () => {+ const invocation = createExampleInvocation()+ service.queueInvocationResults([+ {+ invocation,+ finished: false,+ error: undefined,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ } as any,+ ])+ await service.flush()++ expect(outputs.produce).not.toHaveBeenCalled()+ })+ })++ describe('flush', () => {+ it('uses the invocation_id as the Kafka partition key', async () => {+ const invocation = createExampleInvocation({ id: 'fn-2' })+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()++ const arg = outputs.produce.mock.calls[0][1] as { key: Buffer | null; value: Buffer | null }+ expect(arg.key?.toString('utf8')).toBe(invocation.id)+ })++ it('clears the queue after flush so a second flush is a no-op', async () => {+ const invocation = createExampleInvocation()+ service.queueLifecycleRow(invocation, 'running')+ await service.flush()+ await service.flush()+ expect(outputs.produce).toHaveBeenCalledTimes(1)+ })+ })++ describe('version monotonicity', () => {+ it('produces strictly increasing version values across successive rows for the same invocation', async () => {+ const invocation = createExampleInvocation()+ service.queueLifecycleRow(invocation, 'running')+ // Tick by 1 ms — version is now64(6) in microseconds.+ await new Promise((r) => setTimeout(r, 2))+ service.queueLifecycleRow(invocation, 'succeeded')+ await service.flush()++ const rows = parseProducedRows(outputs)+ expect(rows).toHaveLength(2)+ expect(BigInt(rows[1].version)).toBeGreaterThan(BigInt(rows[0].version))+ })+ })++ // Silence unused import linter noise — DateTime is imported for future tests+ // that exercise queueScheduledAt explicitly.+ void DateTime+})diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.tsnew file mode 100644index 000000000000..d066d53e6eb8--- /dev/null+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts@@ -0,0 +1,484 @@+import { Counter, Gauge } from 'prom-client'++import { HOG_INVOCATION_RESULTS_OUTPUT, HogInvocationResultsOutput } from '~/ingestion/common/outputs'+import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'++import { safeClickhouseString } from '../../../utils/db/utils'+import { logger } from '../../../utils/logger'+import { captureException } from '../../../utils/posthog'+import type { CdpOutput } from '../../cdp-services'+import { RerunFilter, RerunFunctionKind, rerunWrapperKindFor } from '../../rerun/rerun-job.types'+import {+ CyclotronJobInvocation,+ CyclotronJobInvocationHogFlow,+ CyclotronJobInvocationHogFunction,+ CyclotronJobInvocationResult,+} from '../../types'++const counterHogInvocationResultRowsProduced = new Counter({+ name: 'cdp_hog_invocation_result_rows_produced',+ help: 'Lifecycle rows queued for the hog_invocation_results ClickHouse table.',+ labelNames: ['function_kind', 'status'],+})++const counterHogInvocationResultProduceFailed = new Counter({+ name: 'cdp_hog_invocation_result_produce_failed',+ help: 'Rows that failed to produce to Kafka.',+})++const hogInvocationResultsPendingMessages = new Gauge({+ name: 'cdp_hog_invocation_results_pending_messages',+ help: 'Rows queued waiting to be flushed to Kafka.',+})++export type HogInvocationResultsServiceOutput = HogInvocationResultsOutput | CdpOutput++/**+ * Lifecycle row produced to ClickHouse via Kafka. Mirrors the columns on the+ * hog_invocation_results_data table. Two such rows are produced per+ * invocation: one when execution starts (`status='running'`) and one when it+ * finishes (`status='succeeded' | 'failed'`). On a rerun, the cycle repeats+ * with the same `invocation_id`, `is_retry=1`, and `attempts` bumped — the+ * ReplacingMergeTree on `(team_id, function_kind, function_id, invocation_id)`+ * keyed by `version` collapses prior versions at merge time.+ */+export interface HogInvocationResultRow {+ team_id: number+ // `*_rerun` kinds tag the wrapper row that drives a re-run, so the+ // Invocations list can surface in-flight re-runs alongside the function's+ // normal invocations. See `rerun-job.types.ts` for the helper.+ function_kind: 'hog_function' | 'hog_flow' | 'hog_function_rerun' | 'hog_flow_rerun'+ function_id: string+ invocation_id: string+ parent_run_id: string+ status: 'running' | 'succeeded' | 'failed'+ attempts: number+ is_retry: 0 | 1+ scheduled_at: string // ISO microsecond DateTime64+ // Original cyclotron-scheduled time, carried unchanged through retries.+ // ReplacingMergeTree collapses lifecycle rows per invocation_id, so+ // `min(scheduled_at)` post-merge is unreliable — every row stamps this+ // verbatim so `argMax(first_scheduled_at, version)` returns it correctly.+ first_scheduled_at: string+ started_at: string | null+ finished_at: string | null+ duration_ms: number | null+ error_kind: string+ error_message: string+ event_uuid: string+ distinct_id: string+ person_id: string+ invocation_globals: string // pre-serialized JSON+ version: string // microsecond-precision UInt64; serialized as string to dodge JS's 53-bit precision+ is_deleted: 0 | 1+}++const isHogFunctionInvocation = (invocation: CyclotronJobInvocation): invocation is CyclotronJobInvocationHogFunction =>+ 'hogFunction' in invocation++const isHogFlowInvocation = (invocation: CyclotronJobInvocation): invocation is CyclotronJobInvocationHogFlow =>+ 'hogFlow' in invocation++// In-process monotonic counter that breaks ties when consecutive lifecycle+// rows for the same invocation are produced within the same millisecond.+// Without this, the 'running' + terminal rows of a fast invocation can share a+// `version` value, and ReplacingMergeTree keeps one arbitrarily — potentially+// leaving the runs UI showing a permanently 'running' status. We layer+// `performance.now()`'s sub-ms fractional component on top of `Date.now()` to+// stay monotonic within a process; the worst remaining tie window is two+// rows produced at the exact same `performance.now()` sample, which is below+// the precision the clock actually delivers.+const microsecondsSinceEpoch = (): string => {+ // BigInt avoids the 53-bit cap so the number lines up with ClickHouse UInt64.+ const ms = BigInt(Date.now())+ const subMs = BigInt(Math.floor((performance.now() % 1) * 1000))+ return (ms * 1000n + subMs).toString()+}++const isoMicroseconds = (date: Date): string => {+ // ClickHouse DateTime64(6) accepts 'YYYY-MM-DD HH:MM:SS.ffffff'.+ return date.toISOString().replace('T', ' ').replace('Z', '000')+}++const truncate = (value: string, max: number): string => {+ if (value.length <= max) {+ return value+ }+ return value.slice(0, max)+}++// Best-effort error classification — keeps `error_kind` low-cardinality so the+// status_idx skipping index stays small. The full message lands in+// `error_message`, the full stack stays in log_entries.+const classifyError = (error: unknown): { kind: string; message: string } => {+ if (!error) {+ return { kind: '', message: '' }+ }+ const message =+ typeof error === 'string'+ ? error+ : error instanceof Error+ ? error.stack || error.message+ : (() => {+ try {+ return JSON.stringify(error)+ } catch {+ return String(error)+ }+ })()++ const lower = message.toLowerCase()+ let kind = 'hog_error'+ // Anchor the status-code patterns to HTTP-context tokens so messages like+ // "processed 500 items" or "400 rows returned" don't get misclassified as+ // http_5xx / http_4xx. Matches: 'status 503', 'http 502', 'http/2 504',+ // 'status code 500', etc.+ const http5xxRegex = /\b(?:status(?:\s*code)?|http(?:[/ ]\d)?)\s*[:= ]?\s*5\d{2}\b/+ const http4xxRegex = /\b(?:status(?:\s*code)?|http(?:[/ ]\d)?)\s*[:= ]?\s*4\d{2}\b/+ if (lower.includes('timeout') || lower.includes('timed out')) {+ kind = 'timeout'+ } else if (http5xxRegex.test(lower) || lower.includes('server error')) {+ kind = 'http_5xx'+ } else if (http4xxRegex.test(lower)) {+ kind = 'http_4xx'+ } else if (lower.includes('out of memory') || lower.includes('oom')) {+ kind = 'oom'+ }++ return { kind, message: truncate(message, 4096) }+}++const extractTriggerFields = (+ invocation: CyclotronJobInvocation+): { event_uuid: string; distinct_id: string; person_id: string } => {+ if (isHogFunctionInvocation(invocation)) {+ const globals = invocation.state.globals+ return {+ event_uuid: globals.event?.uuid ?? '',+ distinct_id: globals.event?.distinct_id ?? '',+ person_id: globals.person?.id ?? '',+ }+ }++ if (isHogFlowInvocation(invocation)) {+ const event = invocation.state?.event+ return {+ event_uuid: event?.uuid ?? '',+ distinct_id: event?.distinct_id ?? '',+ person_id: invocation.state?.personId ?? invocation.person?.id ?? '',+ }+ }++ return { event_uuid: '', distinct_id: '', person_id: '' }+}++// Strip every `inputs` blob we can find on a globals/state tree. `inputs`+// holds resolved input values for the function — these can include user-+// supplied secrets (API keys, OAuth tokens, etc.) that the function templated+// in at execute time. Persisting them to ClickHouse for 30 days would expand+// the blast radius of any leak. On rerun we re-resolve inputs from the+// current hog function config + integration store, so this is also a no-op+// for rerun correctness — we'll always pick up the latest secrets, not a+// snapshot from when the original invocation ran.+const stripInputs = <T>(value: T): T => {+ if (value === null || typeof value !== 'object') {+ return value+ }+ if (Array.isArray(value)) {+ // We don't expect inputs to live inside arrays today; this branch is a+ // defensive cheap pass-through so a future schema change doesn't have+ // to come back here.+ return value.map((item) => stripInputs(item)) as unknown as T+ }+ const obj = value as Record<string, unknown>+ const out: Record<string, unknown> = {}+ for (const [k, v] of Object.entries(obj)) {+ if (k === 'inputs') {+ continue+ }+ out[k] = stripInputs(v)+ }+ return out as T+}++// The full payload that the rerun path needs to rehydrate the invocation.+// For hog functions this is the globals tree (event, person, groups, etc.) —+// with `inputs` stripped, see `stripInputs`. For hog flows it's the workflow+// context (event, personId, variables, actionStepCount). Worker-side ZSTD+// compression on the ClickHouse column keeps the storage cost down; we+// serialize plain JSON here.+const serializeInvocationGlobals = (invocation: CyclotronJobInvocation): string => {+ if (isHogFunctionInvocation(invocation)) {+ return JSON.stringify(stripInputs(invocation.state.globals))+ }+ if (isHogFlowInvocation(invocation)) {+ // Hog flow state can carry a per-action `currentAction.hogFunctionState.globals.inputs`+ // — `stripInputs` walks the tree and removes those too.+ return JSON.stringify(stripInputs(invocation.state ?? {}))+ }+ return '{}'+}++const sumDurationMs = (invocation: CyclotronJobInvocation): number | null => {+ if (!isHogFunctionInvocation(invocation)) {+ return null+ }+ const timings = invocation.state?.timings+ if (!timings || timings.length === 0) {+ return null+ }+ // Per-step timings are fractional ms (perf.now() deltas). ClickHouse stores+ // duration_ms as UInt32 — Kafka's JSONEachRow parser rejects the row if the+ // field arrives as a float, so round before serialization.+ return Math.round(timings.reduce((sum, t) => sum + t.duration_ms, 0))+}++/**+ * Per-invocation lifecycle row producer. Lives next to+ * `HogFunctionMonitoringService` (which handles aggregated metrics + log+ * lines) — this one writes a single row per lifecycle event so the new+ * runs/invocations UI and the rerun path can read it back via HogQL.+ *+ * Off by default behind `config.HOG_INVOCATION_RESULTS_ENABLED`. Producing+ * rows for filtered-out events is intentionally skipped — the worker only+ * calls into this service for invocations that are actually queued to run.+ */+export class HogInvocationResultsService {+ private queuedRows: HogInvocationResultRow[] = []++ constructor(+ private outputs: IngestionOutputs<HogInvocationResultsServiceOutput>,+ private config: { HOG_INVOCATION_RESULTS_ENABLED: boolean }+ ) {}++ private functionIdFor(invocation: CyclotronJobInvocation): string {+ if (isHogFunctionInvocation(invocation)) {+ return invocation.hogFunction.id+ }+ if (isHogFlowInvocation(invocation)) {+ return invocation.hogFlow.id+ }+ return invocation.functionId+ }++ private functionKindFor(invocation: CyclotronJobInvocation): 'hog_function' | 'hog_flow' {+ return isHogFlowInvocation(invocation) ? 'hog_flow' : 'hog_function'+ }++ /**+ * Queue a lifecycle row. `status='running'` should be called when the+ * worker dequeues an invocation and is about to execute it; `succeeded` /+ * `failed` are derived inside `queueInvocationResults` from the result.+ *+ * `attempts` and `is_retry` are derived from `invocation.state.rerunAttempts`+ * — set by the rerun paginator on rehydration and never touched by the+ * executor's fetch-retry counter (`state.attempts`).+ */+ queueLifecycleRow(+ invocation: CyclotronJobInvocation,+ status: 'running' | 'succeeded' | 'failed',+ opts: {+ error?: unknown+ startedAt?: Date+ finishedAt?: Date+ } = {}+ ): void {+ if (!this.config.HOG_INVOCATION_RESULTS_ENABLED) {+ return+ }++ const now = new Date()+ const trigger = extractTriggerFields(invocation)+ const { kind: errorKind, message: errorMessage } = classifyError(opts.error)+ const startedAt = opts.startedAt ?? (status === 'running' ? now : undefined)+ const finishedAt = opts.finishedAt ?? (status !== 'running' ? now : undefined)+ const durationMs =+ startedAt && finishedAt+ ? Math.max(0, finishedAt.getTime() - startedAt.getTime())+ : sumDurationMs(invocation)+ // Both hog function and hog flow state carry a `rerunAttempts`+ // counter that the rerun paginator increments on rehydration. Read+ // from whichever shape this invocation is so the `max_attempts` guard+ // applies uniformly.+ const rerunAttempts = isHogFunctionInvocation(invocation)+ ? (invocation.state?.rerunAttempts ?? 0)+ : isHogFlowInvocation(invocation)+ ? (invocation.state?.rerunAttempts ?? 0)+ : 0++ // `firstScheduledAt` is set by the rerun paginator on rehydration so+ // retries inherit the original's value; for fresh invocations it's+ // unset and we fall back to the current `scheduled_at`.+ const firstScheduledAtRaw = isHogFunctionInvocation(invocation)+ ? invocation.state?.firstScheduledAt+ : isHogFlowInvocation(invocation)+ ? invocation.state?.firstScheduledAt+ : undefined+ const scheduledAtIso = isoMicroseconds(invocation.queueScheduledAt?.toJSDate() ?? now)++ const row: HogInvocationResultRow = {+ team_id: invocation.teamId,+ function_kind: this.functionKindFor(invocation),+ function_id: this.functionIdFor(invocation),+ invocation_id: invocation.id,+ parent_run_id: invocation.parentRunId ?? '',+ status,+ attempts: rerunAttempts,+ is_retry: rerunAttempts > 0 ? 1 : 0,+ scheduled_at: scheduledAtIso,+ first_scheduled_at: firstScheduledAtRaw ?? scheduledAtIso,+ started_at: startedAt ? isoMicroseconds(startedAt) : null,+ finished_at: finishedAt ? isoMicroseconds(finishedAt) : null,+ duration_ms: durationMs,+ error_kind: errorKind,+ error_message: errorMessage,+ event_uuid: trigger.event_uuid,+ distinct_id: trigger.distinct_id,+ person_id: trigger.person_id,+ invocation_globals: serializeInvocationGlobals(invocation),+ version: microsecondsSinceEpoch(),+ is_deleted: 0,+ }++ counterHogInvocationResultRowsProduced.labels(row.function_kind, row.status).inc()+ this.queuedRows.push(row)+ hogInvocationResultsPendingMessages.set(this.queuedRows.length)+ }++ /**+ * Queue a lifecycle row for a re-run wrapper job.+ *+ * Conceptually a wrapper is a meta-invocation: one row per re-run rather+ * than one per rerun invocation. Stamping it on `hog_invocation_results`+ * (with `function_kind = *_rerun`) means the same Invocations tab is the+ * only debugging surface for both real invocations and the wrappers that+ * spawned them — no separate polling, no separate UI.+ *+ * Fields we deliberately leave empty: `event_uuid` / `distinct_id` /+ * `person_id` — a wrapper isn't triggered by a single event. The filter+ * blob goes in `invocation_globals` (never exposed via HogQL — same+ * security guarantee as for normal invocations).+ */+ queueRerunWrapperRow(args: {+ teamId: number+ parentFunctionKind: RerunFunctionKind+ functionId: string+ rerunJobId: string+ status: 'running' | 'succeeded' | 'failed'+ pagesProcessed: number+ filter: RerunFilter+ scheduledAt: Date+ startedAt?: Date+ finishedAt?: Date+ error?: unknown+ }): void {+ if (!this.config.HOG_INVOCATION_RESULTS_ENABLED) {+ return+ }++ const { kind: errorKind, message: errorMessage } = classifyError(args.error)+ const durationMs =+ args.startedAt && args.finishedAt ? Math.max(0, args.finishedAt.getTime() - args.startedAt.getTime()) : null++ const scheduledAtIso = isoMicroseconds(args.scheduledAt)+ const row: HogInvocationResultRow = {+ team_id: args.teamId,+ function_kind: rerunWrapperKindFor(args.parentFunctionKind),+ function_id: args.functionId,+ invocation_id: args.rerunJobId,+ parent_run_id: '',+ status: args.status,+ attempts: args.pagesProcessed,+ is_retry: 0,+ scheduled_at: scheduledAtIso,+ // Wrapper rows don't have retries — first == scheduled. Keeping+ // the field populated so the column reads consistently across+ // both row kinds.+ first_scheduled_at: scheduledAtIso,+ started_at: args.startedAt ? isoMicroseconds(args.startedAt) : null,+ finished_at: args.finishedAt ? isoMicroseconds(args.finishedAt) : null,+ duration_ms: durationMs,+ error_kind: errorKind,+ error_message: errorMessage,+ event_uuid: '',+ distinct_id: '',+ person_id: '',+ invocation_globals: JSON.stringify(args.filter),+ version: microsecondsSinceEpoch(),+ is_deleted: 0,+ }++ counterHogInvocationResultRowsProduced.labels(row.function_kind, row.status).inc()+ this.queuedRows.push(row)+ hogInvocationResultsPendingMessages.set(this.queuedRows.length)+ }++ queueInvocationResults(results: CyclotronJobInvocationResult[]): void {+ if (!this.config.HOG_INVOCATION_RESULTS_ENABLED) {+ return+ }++ for (const result of results) {+ if (!(result.finished || result.error)) {+ // Mid-flight intermediate update — no terminal row yet. The+ // 'running' row was emitted at execution start; nothing else+ // to write until completion.+ continue+ }++ const status: 'succeeded' | 'failed' = result.error ? 'failed' : 'succeeded'+ this.queueLifecycleRow(result.invocation, status, { error: result.error })+ }+ }++ /**+ * Discard any queued (un-flushed) lifecycle rows for the given invocation+ * ids. Used by the rerun paginator when a re-enqueue is refused (existing+ * job is still in-flight) — we already queued a 'running' row for that+ * invocation_id; drop it so we don't surface a stale running marker.+ */+ dropQueuedRowsFor(invocationIds: string[]): void {+ if (invocationIds.length === 0) {+ return+ }+ const drop = new Set(invocationIds)+ this.queuedRows = this.queuedRows.filter((r) => !drop.has(r.invocation_id))+ hogInvocationResultsPendingMessages.set(this.queuedRows.length)+ }++ async flush(): Promise<void> {+ if (this.queuedRows.length === 0) {+ return+ }++ const rows = this.queuedRows+ this.queuedRows = []+ hogInvocationResultsPendingMessages.set(0)++ await Promise.all(+ rows.map((row) => {+ const value = Buffer.from(safeClickhouseString(JSON.stringify(row)))+ return this.outputs+ .produce(HOG_INVOCATION_RESULTS_OUTPUT, {+ // Partition by invocation_id so all rows for a single+ // invocation land on the same Kafka partition (and+ // therefore the same ClickHouse shard via+ // cityHash64(invocation_id) — keeping the+ // ReplacingMergeTree merge local).+ key: Buffer.from(row.invocation_id),+ value,+ })+ .catch((error) => {+ counterHogInvocationResultProduceFailed.inc()+ // Best-effort — never disrupt invocation processing+ // for a monitoring write.+ logger.error('⚠️', `failed to produce hog invocation result: ${error}`, {+ error: String(error),+ invocation_id: row.invocation_id,+ })+ captureException(error)+ })+ })+ )+ }+}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 3a28e92f1afb..0cee3a448462 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -294,6 +294,17 @@ export type CyclotronJobInvocationHogFunctionContext = {vmState?: VMStatetimings: HogFunctionTiming[]attempts: number // Indicates the number of times this invocation has been attempted (for example if it gets scheduled for retries)+ // Distinct from `attempts` (fetch-retry counter, reset between runs).+ // `rerunAttempts` is incremented when an invocation is rehydrated by the+ // rerun paginator and stays sticky across the entire rerun run. The+ // lifecycle row producer reads this to drive the `attempts` + `is_retry`+ // columns in `hog_invocation_results`.+ rerunAttempts?: number+ // ISO timestamp of the *original* cyclotron-scheduled time. Carried through+ // reruns so the lifecycle row producer can populate `first_scheduled_at`+ // verbatim — ReplacingMergeTree would otherwise collapse retries to the+ // latest version and lose the original.+ firstScheduledAt?: stringactionId?: string // The hogflow action node ID, used for metrics instance_id when executing within a workflow}@@ -319,6 +330,14 @@ export type HogFlowInvocationContext = {hogFunctionState?: CyclotronJobInvocationHogFunctionContext}variables?: Record<string, any>+ // Sticky counter incremented by the rerun paginator on rehydration. Lets+ // the lifecycle row producer derive `attempts` / `is_retry` for hog flows+ // the same way it does for hog functions, so the `max_attempts` guard on+ // the rerun filter actually applies to flows.+ rerunAttempts?: number+ // Carried verbatim through retries so `first_scheduled_at` survives the+ // ReplacingMergeTree collapse on the hog_invocation_results table.+ firstScheduledAt?: string}// Mostly copied from frontend typesdiff --git a/nodejs/src/common/clickhouse-config.ts b/nodejs/src/common/clickhouse-config.tsnew file mode 100644index 000000000000..69d76bec3259--- /dev/null+++ b/nodejs/src/common/clickhouse-config.ts@@ -0,0 +1,34 @@+import { isTestEnv } from '../utils/env-utils'++/**+ * Shared ClickHouse connection config. Service configs that need to talk to+ * ClickHouse compose this type into their own (e.g. `SessionRecordingApiConfig`,+ * `CdpConfig`) so the field set stays in lockstep across services and a service+ * can't silently end up with `undefined` host/db at runtime.+ *+ * Usage:+ * export type MyServiceConfig = ClickhouseConfig & { ... }+ * export function getDefaultMyServiceConfig(): MyServiceConfig {+ * return { ...getDefaultClickhouseConfig(), ... }+ * }+ */+export type ClickhouseConfig = {+ CLICKHOUSE_HOST: string+ CLICKHOUSE_DATABASE: string+ CLICKHOUSE_USER: string+ CLICKHOUSE_PASSWORD: string | undefined+ CLICKHOUSE_SECURE: boolean+}++export function getDefaultClickhouseConfig(): ClickhouseConfig {+ return {+ CLICKHOUSE_HOST: 'localhost',+ // Test runs use the migrated test database — without this default,+ // services that talk to ClickHouse in tests would silently connect to+ // the empty `default` database and find no rows.+ CLICKHOUSE_DATABASE: isTestEnv() ? 'posthog_test' : 'default',+ CLICKHOUSE_USER: 'default',+ CLICKHOUSE_PASSWORD: undefined,+ CLICKHOUSE_SECURE: false,+ }+}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex fdc849f2942d..4faad207aec8 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -34,6 +34,7 @@ export enum PluginServerMode {ingestion_metrics = 'ingestion-metrics',cdp_batch_hogflow_requests = 'cdp-batch-hogflow-requests',cdp_cyclotron_v2_janitor = 'cdp-cyclotron-v2-janitor',+ cdp_rerun_worker = 'cdp-rerun-worker',recording_api = 'recording-api',ingestion_v2_testing = 'ingestion-v2-testing',ingestion_v2_combined = 'ingestion-v2-combined',diff --git a/nodejs/src/config/kafka-topics.ts b/nodejs/src/config/kafka-topics.tsindex 7b31a97fc815..81f4df04fec2 100644--- a/nodejs/src/config/kafka-topics.ts+++ b/nodejs/src/config/kafka-topics.ts@@ -46,6 +46,9 @@ export const KAFKA_CLICKHOUSE_AI_EVENTS_JSON = `${prefix}clickhouse_ai_events_js// log entries for ingestion into ClickHouseexport const KAFKA_LOG_ENTRIES = `${prefix}log_entries${suffix}`+// per-invocation result rows for hog functions and hog flows+export const KAFKA_HOG_INVOCATION_RESULTS = `${prefix}clickhouse_hog_invocation_results${suffix}`+// CDP topicsexport const KAFKA_CDP_FUNCTION_OVERFLOW = `${prefix}cdp_function_overflow${suffix}`export const KAFKA_CDP_INTERNAL_EVENTS = `${prefix}cdp_internal_events${suffix}`diff --git a/nodejs/src/ingestion/common/outputs/index.ts b/nodejs/src/ingestion/common/outputs/index.tsindex 790757477282..32f8483219dd 100644--- a/nodejs/src/ingestion/common/outputs/index.ts+++ b/nodejs/src/ingestion/common/outputs/index.ts@@ -24,6 +24,9 @@ export type LogEntriesOutput = typeof LOG_ENTRIES_OUTPUTexport const TOPHOG_OUTPUT = 'tophog' as constexport type TophogOutput = typeof TOPHOG_OUTPUT+export const HOG_INVOCATION_RESULTS_OUTPUT = 'hog_invocation_results' as const+export type HogInvocationResultsOutput = typeof HOG_INVOCATION_RESULTS_OUTPUT+// Producer names/**diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 217e0db28a68..2c08d2a69d24 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -16,6 +16,7 @@ import { CdpInternalEventsConsumer } from './cdp/consumers/cdp-internal-event.coimport { CdpLegacyEventsConsumer, CdpLegacyEventsConsumerDeps } from './cdp/consumers/cdp-legacy-event.consumer'import { CdpPersonUpdatesConsumer } from './cdp/consumers/cdp-person-updates-consumer'import { CdpPrecalculatedFiltersConsumer } from './cdp/consumers/cdp-precalculated-filters.consumer'+import { CdpRerunWorkerConsumer } from './cdp/consumers/cdp-rerun-worker.consumer'import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'import { CdpProducerName } from './cdp/outputs/producers'import { CyclotronV2JanitorService } from './cdp/services/cyclotron-v2'@@ -31,6 +32,7 @@ import { PluginServerService, PluginsServerConfig, RedisPool } from './types'import { ServerCommands } from './utils/commands'import { PostgresRouter } from './utils/db/postgres'import { createRedisPoolFromConfig } from './utils/db/redis'+import { isDevEnv } from './utils/env-utils'import { GeoIPService } from './utils/geoip'import { logger } from './utils/logger'import { PubSub } from './utils/pubsub'@@ -43,7 +45,7 @@ import { PostgresPersonRepository } from './worker/ingestion/persons/repositorie/*** PluginServer handles CDP, logs, evaluation scheduler, and local-dev combined modes.- * Ingestion is handled by IngestionGeneralServer, recordings by IngestionSessionReplayServer — see index.ts.+ * Ingestion is handled by IngestionGeneralServer, recordings by IngestionSessionRerunServer — see index.ts.*/export class PluginServer implements NodeServer {readonly lifecycle: ServerLifecycle@@ -89,7 +91,8 @@ export class PluginServer implements NodeServer {capabilities.cdpCyclotronWorkerHogFlowLegacyPg ||capabilities.cdpPrecalculatedFilters ||capabilities.cdpCohortMembership ||- capabilities.cdpBatchHogFlow+ capabilities.cdpBatchHogFlow ||+ capabilities.cdpRerunWorker)// 1. Shared infrastructure (always needed)const { teamManager } = await this.createSharedInfrastructure()@@ -189,11 +192,23 @@ export class PluginServer implements NodeServer {}if (capabilities.cdpCyclotronWorker) {- serviceLoaders.push(async () => {- const worker = new CdpCyclotronWorker(this.config, cdpDeps!)- await worker.start()- return worker.service- })+ // Prod deploys one worker per consumer mode (separate pods). Dev runs+ // all three in-process so a single launcher matches prod's fan-out —+ // in particular, rerun re-enqueues land on postgres-v2 because+ // `overwriteExisting: true` always routes there.+ const consumerModes = isDevEnv()+ ? (['kafka', 'postgres', 'postgres-v2'] as const)+ : ([this.config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE] as const)+ for (const mode of consumerModes) {+ serviceLoaders.push(async () => {+ const worker = new CdpCyclotronWorker(+ { ...this.config, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: mode },+ cdpDeps!+ )+ await worker.start()+ return worker.service+ })+ }}if (capabilities.cdpCyclotronV2Janitor) {@@ -219,8 +234,25 @@ export class PluginServer implements NodeServer {}if (capabilities.cdpCyclotronWorkerHogFlow) {+ // Same dev-only fan-out as the worker above.+ const consumerModes = isDevEnv()+ ? (['kafka', 'postgres', 'postgres-v2'] as const)+ : ([this.config.CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE] as const)+ for (const mode of consumerModes) {+ serviceLoaders.push(async () => {+ const worker = new CdpCyclotronWorkerHogFlow(+ { ...this.config, CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: mode },+ cdpDeps!+ )+ await worker.start()+ return worker.service+ })+ }+ }++ if (capabilities.cdpRerunWorker) {serviceLoaders.push(async () => {- const worker = new CdpCyclotronWorkerHogFlow(this.config, cdpDeps!)+ const worker = new CdpRerunWorkerConsumer(this.config, cdpDeps!)await worker.start()return worker.service})diff --git a/nodejs/src/session-recording/config.ts b/nodejs/src/session-recording/config.tsindex ab340834978e..f3da9363e13e 100644--- a/nodejs/src/session-recording/config.ts+++ b/nodejs/src/session-recording/config.ts@@ -1,3 +1,4 @@+import { getDefaultClickhouseConfig } from '../common/clickhouse-config'import {KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,KAFKA_CLICKHOUSE_SESSION_REPLAY_FEATURES,@@ -88,15 +89,11 @@ export type SessionRecordingConfig = {export function getDefaultSessionRecordingApiConfig(): SessionRecordingApiConfig {return {+ ...getDefaultClickhouseConfig(),SESSION_RECORDING_API_REDIS_HOST: '127.0.0.1',SESSION_RECORDING_API_REDIS_PORT: 6379,SESSION_RECORDING_KMS_ENDPOINT: undefined,SESSION_RECORDING_DYNAMODB_ENDPOINT: undefined,- CLICKHOUSE_HOST: 'localhost',- CLICKHOUSE_DATABASE: 'default',- CLICKHOUSE_USER: 'default',- CLICKHOUSE_PASSWORD: undefined,- CLICKHOUSE_SECURE: false,}}diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex 3403158734bd..70508d85c3af 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -173,6 +173,7 @@ export interface PluginServerCapabilities {appManagementSingleton?: booleanevaluationScheduler?: booleancdpCyclotronV2Janitor?: boolean+ cdpRerunWorker?: booleancdpHogflowScheduler?: booleanrecordingApi?: booleaningestionV2Testing?: boolean