Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(cdp): split the hog executor into sync and async services (#77168)

Ben White0b373f27c466
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index 68c990506960..2e12cec83160 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -1706,7 +1706,7 @@ describe('CDP API', () => {
// Stub EmailService so the test doesn't depend on a running maildev SMTP. The spy
// captures whether the inline path was taken — that's the assertion that proves the fix.
emailSpy = jest
- .spyOn(api['hogExecutor']['emailService'], 'executeSendEmail')
+ .spyOn(api['hogExecutorAsync']['deps'].emailService, 'executeSendEmail')
.mockImplementation((invocation: any) =>
Promise.resolve({
invocation,
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index 43a91da3903b..0aaf463cca63 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -35,7 +35,9 @@ import { RerunRequest } from './rerun/rerun-job.types'
import { HogFlowAction } from './schema/hogflow'
import { BatchExportHogFunctionService, NotFoundError, ParseError } from './services/batch-export-hog-function.service'
import type { CyclotronV2JobProducer } from './services/cyclotron-v2'
-import { HogExecutorExecuteAsyncOptions, HogExecutorService, MAX_ASYNC_STEPS } from './services/hog-executor.service'
+import { HogExecutorAsyncService, HogExecutorExecuteAsyncOptions } from './services/hog-executor-async.service'
+import { MAX_ASYNC_STEPS } from './services/hog-executor.service'
+import { HogInputsService } from './services/hog-inputs.service'
import {
BatchResolverState,
HOGFLOW_BATCH_RESOLVE_QUEUE,
@@ -63,6 +65,7 @@ import {
sanitizeLogMessage,
} from './utils'
import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'
+import { buildHogFunctionInvocations } from './utils/invocation-utils'
import { JWT, PosthogJwtAudience } from './utils/jwt-utils'
import { mirrorCall, mirrorCompare } from './utils/mirror-call'
@@ -113,7 +116,8 @@ export type CdpApiConfig = PluginsServerConfig
export type CdpApiDeps = CdpConsumerBaseDeps
export class CdpApi {
- private hogExecutor: HogExecutorService
+ private hogExecutorAsync: HogExecutorAsyncService
+ private hogInputsService: HogInputsService
private nativeDestinationExecutorService: NativeDestinationExecutorService
private segmentDestinationExecutorService: SegmentDestinationExecutorService
@@ -150,7 +154,8 @@ export class CdpApi {
this.hogFunctionManager = services.hogFunctionManager
this.hogFlowManager = services.hogFlowManager
this.recipientTokensService = services.recipientTokensService
- this.hogExecutor = services.hogExecutor
+ this.hogExecutorAsync = services.hogExecutorAsync
+ this.hogInputsService = services.hogInputsService
this.hogFlowExecutor = services.hogFlowExecutor
this.nativeDestinationExecutorService = services.nativeDestinationExecutorService
this.segmentDestinationExecutorService = services.segmentDestinationExecutorService
@@ -182,7 +187,7 @@ export class CdpApi {
deps.teamManager,
this.groupsManager,
this.hogFunctionManager,
- this.hogExecutor,
+ this.hogExecutorAsync,
this.hogWatcher,
this.invocationResultsService,
this.hogWatcherMirror
@@ -483,7 +488,7 @@ export class CdpApi {
invocations,
logs: filterLogs,
metrics: filterMetrics,
- } = await this.hogExecutor.buildHogFunctionInvocations([compoundConfiguration], triggerGlobals)
+ } = await buildHogFunctionInvocations(this.hogInputsService, [compoundConfiguration], triggerGlobals)
// Add metrics to the logs
filterMetrics.forEach((metric) => {
@@ -503,7 +508,7 @@ export class CdpApi {
for (const invocation of invocations) {
invocation.id = invocationID
- const sensitiveValues = this.hogExecutor.getSensitiveValues(
+ const sensitiveValues = this.hogExecutorAsync.hogExecutor.getSensitiveValues(
invocation.hogFunction,
invocation.state.globals.inputs ?? {}
)
@@ -520,7 +525,7 @@ export class CdpApi {
} else if (isSegmentPluginHogFunction(compoundConfiguration)) {
response = await this.segmentDestinationExecutorService.execute(invocation)
} else {
- response = await this.hogExecutor.executeWithAsyncFunctions(invocation, options)
+ response = await this.hogExecutorAsync.executeWithAsyncFunctions(invocation, options)
}
logs = logs.concat(response.logs)
@@ -628,7 +633,7 @@ export class CdpApi {
// Derive from the resolved inputs (which merge inputs + encrypted_inputs) like the
// destination test path does — Django resolves stored secrets into `inputs`, so
// collecting from `encrypted_inputs` alone would leave them unredacted in test logs.
- const sensitiveValues = this.hogExecutor.getSensitiveValues(
+ const sensitiveValues = this.hogExecutorAsync.hogExecutor.getSensitiveValues(
compoundConfiguration,
(hogGlobals.inputs ?? {}) as Record<string, any>
)
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 290fe8c68866..5de5a3aad7c0 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -19,7 +19,8 @@ import {
import { CdpProducerName } from './outputs/producers'
import { createCdpOutputsRegistry } from './outputs/registry'
import { CapturedEventsService } from './services/captured-events/captured-events.service'
-import { HogExecutorService, MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './services/hog-executor.service'
+import { HogExecutorAsyncService } from './services/hog-executor-async.service'
+import { HogExecutorService } from './services/hog-executor.service'
import { HogInputsService } from './services/hog-inputs.service'
import { HogFlowDuplicateObserverService } from './services/hogflows/hogflow-duplicate-observer.service'
import { HogFlowExecutorService } from './services/hogflows/hogflow-executor.service'
@@ -45,6 +46,7 @@ import { HogWatcherService } from './services/monitoring/hog-watcher.service'
import { NativeDestinationExecutorService } from './services/native-destination-executor.service'
import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'
import { WarehouseWebhooksService } from './services/warehouse/warehouse-webhooks.service'
+import { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'
import { EncryptedFields } from './utils/encryption-utils'
/** Union of every output name resolved by `createCdpOutputsRegistry()`. */
@@ -83,7 +85,8 @@ export interface CdpCoreServices {
* `sendEvents: false` so it never emits duplicate billable team events.
*/
hogWatcherMirror: HogWatcherService | null
- hogExecutor: HogExecutorService
+ /** Hog execution with async functions (fetch, email, push). Its `hogExecutor` is the synchronous core. */
+ hogExecutorAsync: HogExecutorAsyncService
/** 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: HogInputsService
hogFunctionTemplateManager: HogFunctionTemplateManagerService
@@ -441,26 +444,29 @@ export function createCdpCoreServices(
valkeyShadow?.writer ?? null
)
- const hogExecutor = new HogExecutorService(
+ const hogExecutorAsync = new HogExecutorAsyncService(
+ new HogExecutorService({ executionTimeoutMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS }, hogInputsService),
{
- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
googleAdwordsDeveloperToken: config.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
fetchRetries: config.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
+ siteUrl: config.SITE_URL,
},
- { teamManager: deps.teamManager, siteUrl: config.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- pushNotificationService
+ {
+ teamManager: deps.teamManager,
+ hogInputsService,
+ emailService,
+ recipientTokensService,
+ pushNotificationService,
+ }
)
const hogFunctionTemplateManager = new HogFunctionTemplateManagerService(deps.postgres)
const hogFlowFunctionsService = new HogFlowFunctionsService(
config.SITE_URL,
hogFunctionTemplateManager,
- hogExecutor
+ hogExecutorAsync
)
const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)
@@ -500,7 +506,7 @@ export function createCdpCoreServices(
hogFlowManager,
hogWatcher,
hogWatcherMirror,
- hogExecutor,
+ hogExecutorAsync,
hogInputsService,
hogFunctionTemplateManager,
hogFlowFunctionsService,
diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
index e115c83bae9d..f498382308f6 100644
--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts
@@ -15,7 +15,7 @@ import {
createCdpCoreServices,
} from '../cdp-services'
import type { CdpConfig } from '../config'
-import { HogExecutorService } from '../services/hog-executor.service'
+import { HogExecutorAsyncService } from '../services/hog-executor-async.service'
import { HogInputsService } from '../services/hog-inputs.service'
import { HogFlowExecutorService } from '../services/hogflows/hogflow-executor.service'
import { HogFlowFunctionsService } from '../services/hogflows/hogflow-functions.service'
@@ -56,7 +56,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
valkeyShadow: CdpValkeyShadowPools | null
isStopping = false
- hogExecutor: HogExecutorService
+ hogExecutorAsync: HogExecutorAsyncService
hogInputsService: HogInputsService
hogFlowExecutor: HogFlowExecutorService
hogMasker: HogMaskerService
@@ -94,7 +94,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd
this.hogFlowManager = services.hogFlowManager
this.hogWatcher = services.hogWatcher
this.hogWatcherMirror = services.hogWatcherMirror
- this.hogExecutor = services.hogExecutor
+ this.hogExecutorAsync = services.hogExecutorAsync
this.hogInputsService = services.hogInputsService
this.hogFunctionTemplateManager = services.hogFunctionTemplateManager
this.hogFlowFunctionsService = services.hogFlowFunctionsService
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
index 94e6b8e80592..9d5b818c76da 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.consumer.ts
@@ -50,7 +50,7 @@ export class CdpCyclotronWorker<
} else if (isSegmentPluginHogFunction(item.hogFunction)) {
return this.segmentDestinationExecutorService.execute(item)
} else {
- return this.hogExecutor.executeWithAsyncFunctions(item)
+ return this.hogExecutorAsync.executeWithAsyncFunctions(item)
}
})
)
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
index bef853453192..0678f1c2349e 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker.test.ts
@@ -139,7 +139,7 @@ describe('CdpCyclotronWorker', () => {
const nativeExecutorSpy = jest.spyOn(processor['nativeDestinationExecutorService'], 'execute')
const pluginExecutorSpy = jest.spyOn(processor['pluginDestinationExecutorService'], 'execute')
const segmentExecutorSpy = jest.spyOn(processor['segmentDestinationExecutorService'], 'execute')
- const hogExecutorSpy = jest.spyOn(processor['hogExecutor'], 'executeWithAsyncFunctions')
+ const hogExecutorSpy = jest.spyOn(processor['hogExecutorAsync'], 'executeWithAsyncFunctions')
const invocations = [
createExampleInvocation(nativeFn, globals),
@@ -474,7 +474,7 @@ describe('CdpCyclotronWorker', () => {
})
)
- processor.hogExecutor['config'].hogCostTimingUpperMs = blockTime
+ processor.hogExecutorAsync.hogExecutor['config'].executionTimeoutMs = blockTime
const numberToTest = 5
const invocations = Array.from({ length: numberToTest }, () =>
diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts
index 15341cb9ac2c..550150bf2f9c 100644
--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts
@@ -49,7 +49,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {
})
this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager: this.hogFunctionManager,
- hogExecutor: this.hogExecutor,
+ hogInputsService: this.hogInputsService,
hogWatcher: this.hogWatcher,
hogWatcherMirror: this.hogWatcherMirror,
hogMasker: this.hogMasker,
diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
index 6424a00c866d..1096cc15b854 100644
--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts
@@ -41,7 +41,7 @@ export class CdpEventsConsumer<
this.kafkaConsumer = createKafkaConsumer({ groupId, topic })
this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager: this.hogFunctionManager,
- hogExecutor: this.hogExecutor,
+ hogInputsService: this.hogInputsService,
hogWatcher: this.hogWatcher,
hogWatcherMirror: this.hogWatcherMirror,
hogMasker: this.hogMasker,
diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
index 53eff969f5bb..3dacfcba00ba 100644
--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
@@ -33,7 +33,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {
})
this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager: this.hogFunctionManager,
- hogExecutor: this.hogExecutor,
+ hogInputsService: this.hogInputsService,
hogWatcher: this.hogWatcher,
hogWatcherMirror: this.hogWatcherMirror,
hogMasker: this.hogMasker,
diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts
index 2818435ba092..182292782f42 100644
--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts
@@ -33,7 +33,7 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {
})
this.hogFunctionPipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager: this.hogFunctionManager,
- hogExecutor: this.hogExecutor,
+ hogInputsService: this.hogInputsService,
hogWatcher: this.hogWatcher,
hogWatcherMirror: this.hogWatcherMirror,
hogMasker: this.hogMasker,
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
index da940bc3ad0f..04f5a9d1d689 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts
@@ -121,7 +121,7 @@ describe('SourceWebhooksConsumer', () => {
hogQueue: createMockJobQueue(),
hogflowQueue: createMockJobQueue(),
})
- mockExecuteSpy = jest.spyOn(api['cdpSourceWebhooksConsumer']['hogExecutor'], 'execute')
+ mockExecuteSpy = jest.spyOn(api['cdpSourceWebhooksConsumer']['hogExecutorAsync'], 'execute')
mockQueueInvocationsSpy = jest.spyOn(api['cdpSourceWebhooksConsumer']['hogQueue'], 'queueInvocations')
mockQueueHogflowInvocationsSpy = jest.spyOn(
api['cdpSourceWebhooksConsumer']['hogflowQueue'],
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
index e8398309d724..347280030d17 100644
--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts
@@ -234,7 +234,10 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
try {
const globals: HogFunctionInvocationGlobals = this.buildRequestGlobals(hogFunction, req)
- const globalsWithInputs = await this.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
+ const globalsWithInputs = await this.hogExecutorAsync.hogExecutor.buildInputsWithGlobals(
+ hogFunction,
+ globals
+ )
const invocation = createInvocation(globalsWithInputs, hogFunction)
// Slightly different handling for hog flows
@@ -345,7 +348,10 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
try {
const globals: HogFunctionInvocationGlobals = this.buildRequestGlobals(hogFunction, req)
- const globalsWithInputs = await this.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
+ const globalsWithInputs = await this.hogExecutorAsync.hogExecutor.buildInputsWithGlobals(
+ hogFunction,
+ globals
+ )
const invocation = createInvocation(globalsWithInputs, hogFunction)
if (hogFunctionState?.state === HogWatcherState.degraded) {
@@ -377,7 +383,7 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf
}
} else {
// Run the initial step - this allows functions not using fetches to respond immediately
- result = await this.hogExecutor.execute(invocation)
+ result = await this.hogExecutorAsync.execute(invocation)
// Queue any queued work here. This allows us to enable delayed work like fetching eventually without blocking the API.
if (!result.finished) {
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
index 0e780241217d..270a712cbc7e 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -16,8 +16,8 @@ import { Hub } from '../../types'
import { createHogFunction, insertHogFunction } from '../_tests/fixtures'
import { posthogPluginGeoip } from '../legacy-plugins/_transformations/posthog-plugin-geoip/template'
import { propertyFilterPlugin } from '../legacy-plugins/_transformations/property-filter-plugin/template'
-import { HogWatcherState } from '../services/monitoring/hog-watcher.service'
import { HogFunctionTemplate } from '../types'
+import type { HogTransformerServiceConfig } from './hog-transformer.service'
import { HogTransformerService, createHogTransformerService } from './hog-transformer.service'
import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
@@ -71,6 +71,26 @@ describe('HogTransformer', () => {
jest.spyOn(hogTransformer['pluginExecutor'], 'execute')
})
+ it('constructs the synchronous executor from only transformation config', async () => {
+ const config: HogTransformerServiceConfig = {
+ SITE_URL: hub.SITE_URL,
+ CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
+ MMDB_FILE_LOCATION: hub.MMDB_FILE_LOCATION,
+ // Deliberately not the default, so the assertion below proves the value is plumbed
+ // through rather than hardcoded in the factory.
+ TRANSFORMATIONS_HOG_TIMEOUT_MS: 123,
+ }
+ const transformer = createHogTransformerService(config, {
+ ...hub,
+ monitoringOutputs: createTestMonitoringOutputs(mockProducer),
+ })
+
+ expect(transformer['hogExecutor']['hogInputsService']['recipientTokensService']).toBeUndefined()
+ expect(transformer['hogExecutor']['config'].executionTimeoutMs).toBe(123)
+
+ await transformer.stop()
+ })
+
describe('transformEvent', () => {
it('handles geoip lookup transformation', async () => {
// Setup the hog function
@@ -1564,356 +1584,18 @@ describe('HogTransformer', () => {
})
})
- describe('HogWatcher integration', () => {
- beforeEach(() => {
- hogTransformer['config'].hogWatcherSampleRate = 1
- })
-
- it('should skip HogWatcher operations when sample rate is 0', async () => {
- hogTransformer['config'].hogWatcherSampleRate = 0
-
- const testTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-test',
- name: 'Test Template',
- description: 'A simple test template',
- category: ['Custom'],
- code_language: 'hog',
- code: `
- let returnEvent := event
- returnEvent.properties.test_property := true
- return returnEvent
- `,
- inputs_schema: [],
- }
-
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: testTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(testTemplate.code),
- id: '11111111-1111-4111-a111-111111111111',
- })
-
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
-
- const observeResultsSpy = jest.spyOn(hogTransformer['hogWatcher'], 'observeResults')
-
- const event = createPluginEvent({ event: 'test-event' }, teamId)
- await hogTransformer.transformEventAndProduceMessages(event)
-
- expect(observeResultsSpy).not.toHaveBeenCalled()
- expect(hogTransformer['invocationResults'].length).toBe(1)
-
- observeResultsSpy.mockRestore()
- })
-
- it('should add watcher promise when sample rate is 1', async () => {
- hogTransformer['config'].hogWatcherSampleRate = 1
-
- const testTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-test',
- name: 'Test Template',
- description: 'A simple test template',
- category: ['Custom'],
- code_language: 'hog',
- code: `
- let returnEvent := event
- returnEvent.properties.test_property := true
- return returnEvent
- `,
- inputs_schema: [],
- }
-
- const hogFunctionId = '11111111-1111-4111-a111-111111111111'
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: testTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(testTemplate.code),
- id: hogFunctionId,
- })
-
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
-
- // Add the state to the cache to prevent the error from being thrown
- // This simulates what would happen in production where states would be loaded
- hogTransformer['cachedStates'][hogFunctionId] = HogWatcherState.healthy
-
- const observeResultsSpy = jest
- .spyOn(hogTransformer['hogWatcher'], 'observeResults')
- .mockImplementation(() => Promise.resolve())
-
- const event = createPluginEvent({ event: 'test-event' }, teamId)
- await hogTransformer.transformEventAndProduceMessages(event)
- expect(hogTransformer['invocationResults'].length).toBe(1)
- await hogTransformer.processInvocationResults()
- expect(hogTransformer['invocationResults'].length).toBe(0)
-
- expect(observeResultsSpy).toHaveBeenCalled()
-
- observeResultsSpy.mockRestore()
- })
-
- it('should save and clear hog function states', async () => {
- const functionIds = ['11111111-1111-4111-a111-111111111111', '22222222-2222-4222-a222-222222222222']
- const mockStates = {
- [functionIds[0]]: { state: HogWatcherState.disabled, tokens: 0, rating: 0 },
- [functionIds[1]]: { state: HogWatcherState.disabled, tokens: 0, rating: 0 },
- }
-
- // Mock getStates
- jest.spyOn(hogTransformer['hogWatcher'], 'getPersistedStates').mockResolvedValue(
- Promise.resolve(mockStates)
- )
-
- // Save states
- await hogTransformer.fetchAndCacheHogFunctionStates(functionIds)
-
- // Verify states were cached
- expect(hogTransformer['cachedStates'][functionIds[0]]).toBe(HogWatcherState.disabled)
- expect(hogTransformer['cachedStates'][functionIds[1]]).toBe(HogWatcherState.disabled)
-
- // Clear specific state
- hogTransformer.clearHogFunctionStates([functionIds[0]])
- expect(hogTransformer['cachedStates'][functionIds[0]]).toBeUndefined()
- expect(hogTransformer['cachedStates'][functionIds[1]]).toBe(HogWatcherState.disabled)
-
- // Clear all states
- hogTransformer.clearHogFunctionStates()
- expect(hogTransformer['cachedStates']).toEqual({})
- })
-
- it('should throw error when state is missing from cache', () => {
- const hogFunctionId = '11111111-1111-4111-a111-111111111111'
-
- // Create a test hog function
- createHogFunction({
- type: 'transformation',
- name: 'Test Function',
- team_id: teamId,
- enabled: true,
- id: hogFunctionId,
- })
-
- // Make sure state is not in cache
- hogTransformer.clearHogFunctionStates()
-
- // Verify state is not in cache initially
- expect(hogTransformer['cachedStates'][hogFunctionId] || null).toBeNull()
-
- // Create the expected error message
- const expectedErrorMessage = `Critical error: Missing HogFunction state in cache for function ${hogFunctionId} - this should never happen`
-
- // Define a function that will throw the error
- const throwingFunction = () => {
- if (!hogTransformer['cachedStates'][hogFunctionId]) {
- throw new Error(expectedErrorMessage)
- }
- return 'This should not be returned'
- }
-
- // Verify that the function throws the expected error
- expect(throwingFunction).toThrow(expectedErrorMessage)
- })
-
- it('should skip transformation execution but continue when hogwatcher is enabled and function is disabled', async () => {
- // Set sample rate to 100% to ensure hogwatcher logic runs
- hogTransformer['config'].hogWatcherSampleRate = 1
-
- // Create test transformation function
- const testTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-test',
- name: 'Disabled Test Template',
- description: 'A test template that should be skipped due to disabled state',
- category: ['Custom'],
- code_language: 'hog',
- code: `
- let returnEvent := event
- returnEvent.properties.should_not_be_set := true
- return returnEvent
- `,
- inputs_schema: [],
- }
-
- const hogFunctionId = '33333333-3333-4333-a333-333333333333'
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: testTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(testTemplate.code),
- id: hogFunctionId,
- })
-
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
-
- // Mock the cached state to indicate the function is disabled
- hogTransformer['cachedStates'][hogFunctionId] = HogWatcherState.disabled
-
- // Create a spy to verify the executeHogFunction method is not called
- const executeHogFunctionSpy = jest.spyOn(hogTransformer as any, 'executeHogFunction')
-
- const event = createPluginEvent({ event: 'test-event' }, teamId)
- const result = await hogTransformer.transformEventAndProduceMessages(event)
-
- // Verify the executeHogFunction method was not called for this function
- expect(executeHogFunctionSpy).not.toHaveBeenCalled()
-
- // Verify the transformation result doesn't have the property that would be set
- expect(result.event?.properties?.should_not_be_set).toBeUndefined()
-
- // Verify there are no transformation records in the properties
- expect(result.event?.properties?.$transformations_succeeded).toBeUndefined()
- expect(result.event?.properties?.$transformations_failed).toBeUndefined()
-
- // Reset spies
- executeHogFunctionSpy.mockRestore()
- })
-
- it('should execute transformation when hogwatcher is enabled but function is in healthy state', async () => {
- // Set sample rate to 100% to ensure hogwatcher logic runs
- hogTransformer['config'].hogWatcherSampleRate = 1
-
- // Create test transformation function
- const testTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-test',
- name: 'Healthy Test Template',
- description: 'A test template that should execute because state is healthy',
- category: ['Custom'],
- code_language: 'hog',
- code: `
- let returnEvent := event
- returnEvent.properties.should_be_set := true
- return returnEvent
- `,
- inputs_schema: [],
- }
-
- const hogFunctionId = '55555555-5555-5555-a555-555555555555'
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: testTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(testTemplate.code),
- id: hogFunctionId,
- })
-
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
-
- // Mock the cached state to indicate the function is healthy
- hogTransformer['cachedStates'][hogFunctionId] = HogWatcherState.healthy
-
- // Create a spy to verify the executeHogFunction method is called
- const executeHogFunctionSpy = jest.spyOn(hogTransformer as any, 'executeHogFunction')
-
- const event = createPluginEvent({ event: 'test-event' }, teamId)
- const result = await hogTransformer.transformEventAndProduceMessages(event)
-
- // Verify the executeHogFunction method was called for this function
- expect(executeHogFunctionSpy).toHaveBeenCalledTimes(1)
-
- // Verify the transformation result has the property that should be set
- expect(result.event?.properties?.should_be_set).toBe(true)
-
- // Verify the transformation is recorded as successful
- expect(result.event?.properties?.$transformations_succeeded).toContain(
- `${hogFunction.name} (${hogFunction.id})`
- )
-
- // Reset spies
- executeHogFunctionSpy.mockRestore()
- })
-
- it('should apply transformation when hogwatcher is disabled even if function state is disabled', async () => {
- // Set sample rate to 0% to ensure hogwatcher logic is skipped
- hogTransformer['config'].hogWatcherSampleRate = 0
-
- // Create test transformation function
- const testTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-test',
- name: 'Test Template',
- description: 'A test template that should execute despite disabled state because hogwatcher is off',
- category: ['Custom'],
- code_language: 'hog',
- code: `
- let returnEvent := event
- returnEvent.properties.should_be_set := true
- return returnEvent
- `,
- inputs_schema: [],
- }
-
- const hogFunctionId = '44444444-4444-4444-a444-444444444444'
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: testTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(testTemplate.code),
- id: hogFunctionId,
- })
-
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
-
- // Mock the cached state to indicate the function is disabled
- hogTransformer['cachedStates'][hogFunctionId] = HogWatcherState.disabled
-
- // Create a spy to verify the executeHogFunction method is called
- const executeHogFunctionSpy = jest.spyOn(hogTransformer as any, 'executeHogFunction')
-
- const event = createPluginEvent({ event: 'test-event' }, teamId)
- const result = await hogTransformer.transformEventAndProduceMessages(event)
-
- // Verify the executeHogFunction method was called for this function
- expect(executeHogFunctionSpy).toHaveBeenCalledTimes(1)
-
- // Verify the transformation result has the property that should be set
- expect(result.event?.properties?.should_be_set).toBe(true)
-
- // Verify the transformation is recorded as successful
- expect(result.event?.properties?.$transformations_succeeded).toContain(
- `${hogFunction.name} (${hogFunction.id})`
- )
-
- // Reset spies
- executeHogFunctionSpy.mockRestore()
- })
-
- it('should throw when trying to capture events in transformations', async () => {
- // Create a transformation function that captures an event
- const captureTemplate: HogFunctionTemplate = {
- free: true,
- status: 'beta',
- type: 'transformation',
- id: 'template-capture',
- name: 'Capture Template',
- description: 'A template that captures an event',
- category: ['Custom'],
- code_language: 'hog',
- code: `
+ it('should throw when trying to capture events in transformations', async () => {
+ // Create a transformation function that captures an event
+ const captureTemplate: HogFunctionTemplate = {
+ free: true,
+ status: 'beta',
+ type: 'transformation',
+ id: 'template-capture',
+ name: 'Capture Template',
+ description: 'A template that captures an event',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
let returnEvent := event
returnEvent.properties.captured := true
@@ -1931,26 +1613,25 @@ describe('HogTransformer', () => {
return returnEvent
`,
- inputs_schema: [],
- }
-
- const hogFunction = createHogFunction({
- type: 'transformation',
- name: captureTemplate.name,
- team_id: teamId,
- enabled: true,
- bytecode: await compileHog(captureTemplate.code),
- id: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa',
- })
+ inputs_schema: [],
+ }
+
+ const hogFunction = createHogFunction({
+ type: 'transformation',
+ name: captureTemplate.name,
+ team_id: teamId,
+ enabled: true,
+ bytecode: await compileHog(captureTemplate.code),
+ id: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa',
+ })
- await insertHogFunction(hub.postgres, teamId, hogFunction)
- hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
+ await insertHogFunction(hub.postgres, teamId, hogFunction)
+ hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
- const event = createPluginEvent({ event: 'original-event', distinct_id: 'original_user' }, teamId)
- const result = await hogTransformer.transformEventAndProduceMessages(event)
+ const event = createPluginEvent({ event: 'original-event', distinct_id: 'original_user' }, teamId)
+ const result = await hogTransformer.transformEventAndProduceMessages(event)
- expect(result.invocationResults[0].error).toContain('posthogCapture is not supported in transformations')
- })
+ expect(result.invocationResults[0].error).toContain('posthogCapture is not supported in transformations')
})
describe('rust vm primary execution', () => {
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 860b545f2f2d..16e379f8e196 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -1,44 +1,31 @@
-import { Counter, Gauge, Histogram } from 'prom-client'
+import { Counter, Gauge } from 'prom-client'
import { HogTransformationResult, HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { instrumentFn } from '~/common/tracing/tracing-utils'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { GeoIPService, GeoIp } from '~/common/utils/geoip'
import { logger } from '~/common/utils/logger'
import { PubSub } from '~/common/utils/pubsub'
-import { TeamManager } from '~/common/utils/team-manager'
import { PluginEvent } from '~/plugin-scaffold'
import { CyclotronJobInvocationResult, HogFunctionInvocationGlobals, HogFunctionType } from '../../cdp/types'
import { isLegacyPluginHogFunction } from '../../cdp/utils'
import type { CommonConfig } from '../../common/config'
-import { CdpCoreServicesConfig, createCdpReaderRedisPool, createCdpValkeyShadowPools } from '../cdp-services'
-import { HogExecutorService, MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from '../services/hog-executor.service'
+import { HogExecutorService } from '../services/hog-executor.service'
import { HogInputsService } from '../services/hog-inputs.service'
import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'
import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'
import { IntegrationManagerService } from '../services/managers/integration-manager.service'
-import { RecipientsManagerService } from '../services/managers/recipients-manager.service'
-import { TeamWorkflowsConfigService } from '../services/managers/team-workflows-config.service'
-import { EmailSuppressionService } from '../services/messaging/email-suppression.service'
-import { EmailService } from '../services/messaging/email.service'
-import { EmailTrackingCodeSigner } from '../services/messaging/helpers/tracking-code'
-import { PushNotificationService } from '../services/messaging/push-notification.service'
-import { RecipientTokensService } from '../services/messaging/recipient-tokens.service'
import { HogFunctionMonitoringService, MonitoringOutput } from '../services/monitoring/hog-function-monitoring.service'
-import { HogWatcherService, HogWatcherState } from '../services/monitoring/hog-watcher.service'
import { EncryptedFields } from '../utils/encryption-utils'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'
import { createInvocation } from '../utils/invocation-utils'
-import { mirrorCall } from '../utils/mirror-call'
import { RustVmExecutor } from './rust-vm-executor'
import { getTransformationFunctions } from './transformation-functions'
export interface HogTransformerConfig {
siteUrl: string
- hogWatcherSampleRate: number
hogRustVmExecutionEnabled: boolean
mmdbFileLocation: string
}
@@ -65,12 +52,6 @@ export const hogTransformationCompleted = new Counter({
labelNames: ['type'],
})
-export const hogWatcherLatency = new Histogram({
- name: 'hog_watcher_latency_seconds',
- help: 'Time spent in HogWatcher operations in seconds during ingestion',
- labelNames: ['operation'],
-})
-
export const hogTransformationPendingInvocationResults = new Gauge({
name: 'hog_transformation_pending_invocation_results',
help: 'Number of invocation results accumulated and waiting to be processed. High values indicate memory accumulation.',
@@ -87,7 +68,6 @@ export interface TransformationResult extends HogTransformationResult {
}
export class HogTransformerService implements HogTransformer {
- private cachedStates: Record<string, HogWatcherState> = {}
private invocationResults: CyclotronJobInvocationResult[] = []
private cachedGeoIp?: GeoIp
private cachedTransformationFunctions?: ReturnType<typeof getTransformationFunctions>
@@ -96,12 +76,9 @@ export class HogTransformerService implements HogTransformer {
constructor(
private hogFunctionManager: HogFunctionManagerService,
private hogExecutor: HogExecutorService,
- private hogWatcher: HogWatcherService,
- private hogWatcherMirror: HogWatcherService | null,
private hogFunctionMonitoringService: HogFunctionMonitoringService,
private pluginExecutor: LegacyPluginExecutorService,
private geoipService: GeoIPService,
- private redis: RedisV2,
private config: HogTransformerConfig
) {
this.rustVmExecutor = config.hogRustVmExecutionEnabled
@@ -113,9 +90,6 @@ export class HogTransformerService implements HogTransformer {
public async stop(): Promise<void> {
await this.processInvocationResults()
- await this.redis.useClient({ name: 'cleanup' }, async (client) => {
- await client.quit()
- })
}
public async processInvocationResults(): Promise<void> {
@@ -123,23 +97,9 @@ export class HogTransformerService implements HogTransformer {
this.invocationResults = []
hogTransformationPendingInvocationResults.set(0)
- const shouldRunHogWatcher = Math.random() < this.config.hogWatcherSampleRate
-
this.hogFunctionMonitoringService.queueInvocationResults(results)
- await Promise.allSettled([
- this.hogFunctionMonitoringService.flush(),
-
- shouldRunHogWatcher
- ? this.hogWatcher.observeResults(results).catch((error) => {
- logger.warn('⚠️', 'HogWatcher observeResults failed', { error })
- })
- : Promise.resolve(),
-
- shouldRunHogWatcher
- ? mirrorCall('hog-watcher.observeResults', () => this.hogWatcherMirror?.observeResults(results))
- : Promise.resolve(),
- ])
+ await this.hogFunctionMonitoringService.flush()
}
private async getTransformationFunctions() {
@@ -212,33 +172,10 @@ export class HogTransformerService implements HogTransformer {
const transformationsFailed: string[] = []
const transformationsSkipped: string[] = []
- const shouldRunHogWatcher = Math.random() < this.config.hogWatcherSampleRate
-
// Create globals once and update the event properties after each transformation
const globals = this.createInvocationGlobals(event)
for (const hogFunction of teamHogFunctions) {
- // Check if function is in a degraded state, but only if hogwatcher is enabled
- if (shouldRunHogWatcher) {
- const functionState = this.cachedStates[hogFunction.id]
-
- // If the function is in a degraded state, skip it
- if (functionState && functionState === HogWatcherState.disabled) {
- this.hogFunctionMonitoringService.queueAppMetric(
- {
- team_id: event.team_id,
- app_source_id: hogFunction.id,
- metric_kind: 'failure',
- metric_name: 'disabled_permanently',
- count: 1,
- },
- 'hog_function'
- )
- continue
- }
- }
-
- // Create identifier after the disabled check passes to avoid string allocation for skipped functions
const transformationIdentifier = `${hogFunction.name} (${hogFunction.id})`
// Create filterGlobals for each iteration - it references globals.event.properties
@@ -425,58 +362,15 @@ export class HogTransformerService implements HogTransformer {
}
}
- return await this.hogExecutor.execute(invocation, {
- functions: transformationFunctions,
- asyncFunctionsNames: [],
- })
- }
-
- public async fetchAndCacheHogFunctionStates(functionIds: string[]): Promise<void> {
- const timer = hogWatcherLatency.startTimer({ operation: 'getStates' })
- const [states] = await Promise.all([
- this.hogWatcher.getEffectiveStates(functionIds),
- mirrorCall('hog-watcher.getEffectiveStates', () => this.hogWatcherMirror?.getEffectiveStates(functionIds)),
- ])
- timer()
-
- // Save only the state enum value to cache
- Object.entries(states).forEach(([id, state]) => {
- this.cachedStates[id] = state.state
- })
- }
-
- public clearHogFunctionStates(functionIds?: string[]): void {
- if (functionIds) {
- // Clear specific function states
- functionIds.forEach((id) => {
- delete this.cachedStates[id]
- })
- } else {
- // Clear all states if no IDs provided
- this.cachedStates = {}
- }
- }
-
- public async prefetchTransformationStatesForTeams(teamIds: number[]): Promise<void> {
- this.clearHogFunctionStates()
- if (teamIds.length === 0) {
- return
- }
- const teamHogFunctionIds = await this.hogFunctionManager.getHogFunctionIdsForTeams(teamIds, ['transformation'])
- const allHogFunctionIds = Object.values(teamHogFunctionIds).flat()
- if (allHogFunctionIds.length > 0) {
- await this.fetchAndCacheHogFunctionStates(allHogFunctionIds)
- }
+ return await this.hogExecutor.execute(invocation, { functions: transformationFunctions })
}
}
-/**
- * Config needed by the HogTransformer when running inside ingestion.
- * This is CdpCoreServicesConfig (CDP redis, watcher, monitoring, encryption, etc.)
- * plus the ingestion-specific sample rates from CommonConfig.
- */
-export type HogTransformerServiceConfig = CdpCoreServicesConfig &
- Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE' | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED' | 'MMDB_FILE_LOCATION'>
+/** Config read by createHogTransformerService when running inside ingestion. */
+export type HogTransformerServiceConfig = Pick<
+ CommonConfig,
+ 'SITE_URL' | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED' | 'MMDB_FILE_LOCATION' | 'TRANSFORMATIONS_HOG_TIMEOUT_MS'
+>
export interface HogTransformerServiceDeps {
geoipService: GeoIPService
@@ -485,121 +379,33 @@ export interface HogTransformerServiceDeps {
encryptedFields: EncryptedFields
integrationManager: IntegrationManagerService
monitoringOutputs: IngestionOutputs<MonitoringOutput>
- teamManager: TeamManager
}
+/**
+ * Keep this factory's config and dependencies intentionally minimal. Transformations run only the synchronous Hog
+ * execution core and must not inherit Redis, fetch, email, push, or other CDP delivery infrastructure just to satisfy
+ * a shared service constructor. Anything that needs those belongs in HogExecutorAsyncService, not in HogExecutorService.
+ */
export function createHogTransformerService(
config: HogTransformerServiceConfig,
deps: HogTransformerServiceDeps
): HogTransformerService {
- const redis = createRedisV2PoolFromConfig({
- connection: config.CDP_REDIS_HOST
- ? {
- url: config.CDP_REDIS_HOST,
- options: { port: config.CDP_REDIS_PORT, password: config.CDP_REDIS_PASSWORD },
- name: 'hog-transformer-redis',
- }
- : { url: config.REDIS_URL, name: 'hog-transformer-redis-fallback' },
- poolMinSize: config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: config.REDIS_POOL_MAX_SIZE,
- })
- const redisReader = createCdpReaderRedisPool(config, redis, 'hog-transformer-redis')
- const valkeyShadow = createCdpValkeyShadowPools(config, 'hog-transformer-redis')
-
const hogFunctionManager = new HogFunctionManagerService(deps.postgres, deps.pubSub, deps.encryptedFields)
- const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
- const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)
- const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)
- const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)
- const emailSuppressionService = new EmailSuppressionService(deps.postgres, {
- transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,
- })
- const emailService = new EmailService(
- {
- sesAccessKeyId: config.SES_ACCESS_KEY_ID,
- sesSecretAccessKey: config.SES_SECRET_ACCESS_KEY,
- sesRegion: config.SES_REGION,
- sesEndpoint: config.SES_ENDPOINT,
- sesTrackedConfigurationSet: config.SES_TRACKED_CONFIGURATION_SET,
- sesUntrackedConfigurationSet: config.SES_UNTRACKED_CONFIGURATION_SET,
- sesTenantAttributionEnabled: config.EMAIL_SES_TENANT_ATTRIBUTION_ENABLED,
- },
- deps.integrationManager,
- teamWorkflowsConfigService,
- config.ENCRYPTION_SALT_KEYS,
- config.SITE_URL,
- trackingCodeSigner,
- emailSuppressionService,
- new RecipientsManagerService(deps.postgres)
- )
- const pushNotificationService = new PushNotificationService(
- deps.integrationManager,
- deps.encryptedFields,
- {
- trackedFetch: cdpTrackedFetch,
- maxFetchTimeoutMs: MAX_FETCH_TIMEOUT_MS,
- maxRetries: config.CDP_FETCH_RETRIES,
- backoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
- backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
- },
- redis
- )
+ const hogInputsService = new HogInputsService(deps.integrationManager, undefined, deps.encryptedFields)
const hogExecutor = new HogExecutorService(
- {
- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
- googleAdwordsDeveloperToken: config.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
- fetchRetries: config.CDP_FETCH_RETRIES,
- fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
- fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
- },
- { teamManager: deps.teamManager, siteUrl: config.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- pushNotificationService
+ { executionTimeoutMs: config.TRANSFORMATIONS_HOG_TIMEOUT_MS },
+ hogInputsService
)
const pluginExecutor = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)
const hogFunctionMonitoringService = new HogFunctionMonitoringService(deps.monitoringOutputs)
- const hogWatcherConfig = {
- hogCostTimingLowerMs: config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,
- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
- hogCostTiming: config.CDP_WATCHER_HOG_COST_TIMING,
- asyncCostTimingLowerMs: config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,
- asyncCostTimingUpperMs: config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,
- asyncCostTiming: config.CDP_WATCHER_ASYNC_COST_TIMING,
- sendEvents: config.CDP_WATCHER_SEND_EVENTS,
- bucketSize: config.CDP_WATCHER_BUCKET_SIZE,
- refillRate: config.CDP_WATCHER_REFILL_RATE,
- ttl: config.CDP_WATCHER_TTL,
- automaticallyDisableFunctions: config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,
- thresholdDegraded: config.CDP_WATCHER_THRESHOLD_DEGRADED,
- stateLockTtl: config.CDP_WATCHER_STATE_LOCK_TTL,
- observeResultsBufferTimeMs: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,
- observeResultsBufferMaxResults: config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,
- }
- const hogWatcher = new HogWatcherService(deps.teamManager, hogWatcherConfig, redis, redisReader)
- // sendEvents:false on the mirror so we don't double-emit billable team events.
- const hogWatcherMirror: HogWatcherService | null = valkeyShadow
- ? new HogWatcherService(
- deps.teamManager,
- { ...hogWatcherConfig, sendEvents: false },
- valkeyShadow.writer,
- valkeyShadow.reader
- )
- : null
-
return new HogTransformerService(
hogFunctionManager,
hogExecutor,
- hogWatcher,
- hogWatcherMirror,
hogFunctionMonitoringService,
pluginExecutor,
deps.geoipService,
- redis,
{
siteUrl: config.SITE_URL,
- hogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,
hogRustVmExecutionEnabled: config.CDP_HOG_RUST_VM_EXECUTION_ENABLED,
mmdbFileLocation: config.MMDB_FILE_LOCATION,
}
diff --git a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
index 7e47cca9cfa5..01f1e85625e7 100644
--- a/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
+++ b/nodejs/src/cdp/legacy-webhooks/legacy-webhook-service.ts
@@ -12,7 +12,7 @@ import { Action, Hook, HookPayload, PostIngestionEvent, RawClickHouseEvent, RawK
import { counterParseError } from '../consumers/metrics'
import { ActionManager } from '../legacy-webhooks/action-manager'
import { ActionMatcher } from '../legacy-webhooks/action-matcher'
-import { cdpTrackedFetch } from '../services/hog-executor.service'
+import { cdpTrackedFetch } from '../utils/cdp-fetch'
export class LegacyWebhookService {
protected actionManager: ActionManager
diff --git a/nodejs/src/cdp/segment/segment-templates.ts b/nodejs/src/cdp/segment/segment-templates.ts
index ec43d6313988..d17eb591ecca 100644
--- a/nodejs/src/cdp/segment/segment-templates.ts
+++ b/nodejs/src/cdp/segment/segment-templates.ts
@@ -2,7 +2,7 @@ import { DestinationDefinition, destinations } from '@segment/action-destination
import { HogFunctionFilterEvent, HogFunctionInputSchemaType, HogFunctionTemplate } from '~/cdp/types'
-import { EXTEND_OBJECT_KEY } from '../services/hog-executor.service'
+import { EXTEND_OBJECT_KEY } from '../services/hog-inputs.service'
export type SegmentDestination = {
template: HogFunctionTemplate
diff --git a/nodejs/src/cdp/services/batch-export-hog-function.service.ts b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
index e9e466544097..942172ddff1d 100644
--- a/nodejs/src/cdp/services/batch-export-hog-function.service.ts
+++ b/nodejs/src/cdp/services/batch-export-hog-function.service.ts
@@ -14,7 +14,7 @@ import {
import { convertToHogFunctionInvocationGlobals } from '../utils'
import { createInvocation } from '../utils/invocation-utils'
import { mirrorCall } from '../utils/mirror-call'
-import { HogExecutorService } from './hog-executor.service'
+import { HogExecutorAsyncService } from './hog-executor-async.service'
import { InvocationResultsService } from './invocation-results.service'
import { GroupsManagerService } from './managers/groups-manager.service'
import { HogFunctionManagerService } from './managers/hog-function-manager.service'
@@ -45,7 +45,7 @@ export class BatchExportHogFunctionService {
private teamManager: TeamManager,
private groupsManager: GroupsManagerService,
private hogFunctionManager: HogFunctionManagerService,
- private hogExecutor: HogExecutorService,
+ private hogExecutorAsync: HogExecutorAsyncService,
private hogWatcher: HogWatcherService,
private invocationResultsService: InvocationResultsService,
private hogWatcherMirror: HogWatcherService | null = null
@@ -86,11 +86,11 @@ export class BatchExportHogFunctionService {
const globals = this.buildRequestGlobals(clickhouse_event as RawClickHouseEvent, hogFunction, team)
await this.groupsManager.addGroupsToGlobals(globals)
- const globalsWithInputs = await this.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
+ const globalsWithInputs = await this.hogExecutorAsync.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
const invocation = createInvocation(globalsWithInputs, hogFunction)
invocation.id = invocationId.toString()
- const result = await this.hogExecutor.executeWithAsyncFunctions(invocation, { maxFetchRetries: 0 }) // Retries are handled by the batch export service
+ const result = await this.hogExecutorAsync.executeWithAsyncFunctions(invocation, { maxFetchRetries: 0 }) // Retries are handled by the batch export service
// TODO: Follow up - we might want to more accuratelt link an execution to the fact it came from a batch export
// We have the parent_id but that overrides the function id which is not always what we want
diff --git a/nodejs/src/cdp/services/hog-executor-async.service.ts b/nodejs/src/cdp/services/hog-executor-async.service.ts
new file mode 100644
index 000000000000..450f2247128b
--- /dev/null
+++ b/nodejs/src/cdp/services/hog-executor-async.service.ts
@@ -0,0 +1,518 @@
+import { DateTime } from 'luxon'
+import { Counter } from 'prom-client'
+
+import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
+import { instrumented } from '~/common/tracing/tracing-utils'
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
+import { FetchOptions } from '~/common/utils/request'
+import { TeamManager } from '~/common/utils/team-manager'
+
+import { getAsyncFunctionHandler, getRegisteredAsyncFunctionNames } from '../async-function-registry'
+import '../async-functions'
+import type {
+ CyclotronJobInvocationHogFunction,
+ CyclotronJobInvocationResult,
+ MinimalAppMetric,
+ MinimalLogEntry,
+} from '../types'
+import { createAddLogFunction, destinationE2eLagMsSummary } from '../utils'
+import { resolveAwsSigV4Credentials, signAwsRequest } from '../utils/aws-sigv4'
+import { cdpTrackedFetch, isFetchResponseRetriable } from '../utils/cdp-fetch'
+import { createInvocationResult } from '../utils/invocation-utils'
+import { isNonFailureStatus } from '../utils/non-failure-status-codes'
+import { HogExecutorExecuteOptions, HogExecutorPreviousResult, HogExecutorService } from './hog-executor.service'
+import { HogInputsService } from './hog-inputs.service'
+import { EmailService } from './messaging/email.service'
+import { PushNotificationService } from './messaging/push-notification.service'
+import { RecipientTokensService } from './messaging/recipient-tokens.service'
+import {
+ SELF_LOOP_MAX_DEPTH,
+ getSelfLoopDepth,
+ injectSelfLoopDepth,
+ isPostHogIngestUrl,
+ isSelfReferentialIngestFetch,
+ selfLoopGuardCounter,
+} from './self-loop-guard'
+
+const cdpEmailQueuedTotal = new Counter({
+ name: 'cdp_email_queued_total',
+ help: 'Total emails routed to the dedicated email queue',
+})
+
+export interface HogExecutorAsyncConfig {
+ googleAdwordsDeveloperToken: string
+ fetchRetries: number
+ fetchBackoffBaseMs: number
+ fetchBackoffMaxMs: number
+ siteUrl: string
+}
+
+/**
+ * Every capability the async functions can reach is required - an async executor missing one is a
+ * misconfiguration, not a supported mode, and would only surface as a runtime throw deep inside a
+ * customer's function. Callers that don't need any of them want HogExecutorService directly.
+ */
+export interface HogExecutorAsyncDependencies {
+ teamManager: TeamManager
+ hogInputsService: HogInputsService
+ emailService: EmailService
+ recipientTokensService: RecipientTokensService
+ pushNotificationService: PushNotificationService
+}
+
+export type HogExecutorExecuteAsyncOptions = HogExecutorExecuteOptions & {
+ maxAsyncFunctions?: number
+ maxFetchRetries?: number
+ // Set only by the editor's test panel ("Run test"), marking this invocation as a test send. Two
+ // effects: emails run inline via EmailService instead of routing to the email queue (the test
+ // endpoint executes in-process and never enqueues to cyclotron, so routing would leave the job
+ // unworked), and messaging channels skip metrics/assets so a test doesn't pollute the workflow's
+ // Metrics and Assets tabs.
+ isTest?: boolean
+}
+
+/**
+ * Hog execution plus everything a function needs to suspend and resume: fetches, emails, push
+ * notifications, and the queue routing between the workers that service them.
+ *
+ * The synchronous Hog core is exposed as `hogExecutor` rather than re-wrapped, so callers reach
+ * `buildInputsWithGlobals` / `buildHogFunctionInvocations` / `getSensitiveValues` on the thing that
+ * actually owns them.
+ */
+export class HogExecutorAsyncService {
+ constructor(
+ public readonly hogExecutor: HogExecutorService,
+ private config: HogExecutorAsyncConfig,
+ private deps: HogExecutorAsyncDependencies
+ ) {}
+
+ @instrumented('hog-executor.executeWithAsyncFunctions')
+ async executeWithAsyncFunctions(
+ invocation: CyclotronJobInvocationHogFunction,
+ options?: HogExecutorExecuteAsyncOptions
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
+ let asyncFunctionCount = 0
+ const maxAsyncFunctions = options?.maxAsyncFunctions ?? 1
+
+ let result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null = null
+ const metrics: MinimalAppMetric[] = []
+ const logs: MinimalLogEntry[] = []
+
+ while (!result || !result.finished) {
+ const nextInvocation: CyclotronJobInvocationHogFunction = result?.invocation ?? invocation
+
+ const queueParamsType = nextInvocation.queueParameters?.type
+ if (['fetch', 'sendPushNotification', 'email'].includes(queueParamsType ?? '')) {
+ asyncFunctionCount++
+
+ if (result && asyncFunctionCount > maxAsyncFunctions) {
+ // We don't want to block the consumer too much hence we have a limit on async functions
+ logger.debug('🦔', `[HogExecutor] Max async functions reached: ${maxAsyncFunctions}`)
+ break
+ }
+
+ // Queue-aware routing: each worker can execute some actions inline
+ // and routes others to a specialized queue. The email worker sends
+ // emails inline but routes fetches back to hogflow. The hogflow
+ // worker does fetches inline but routes emails to the email queue.
+ //
+ // Future: once we add an execution time budget, the email worker
+ // will also handle fetches inline. The only reason to reschedule
+ // back to hogflow will be when overall execution time exceeds the
+ // budget, to avoid blocking the queue.
+ if (queueParamsType === 'fetch') {
+ if (invocation.queue === 'email') {
+ result = this.routeToQueue(
+ nextInvocation,
+ nextInvocation.queueMetadata?.originQueue ?? 'hogflow'
+ )
+ } else {
+ result = await this.executeFetch(nextInvocation, options)
+ }
+ } else if (queueParamsType === 'sendPushNotification') {
+ result = await this.deps.pushNotificationService.executeSendPushNotification(
+ nextInvocation,
+ options?.isTest ?? false
+ )
+ } else if (queueParamsType === 'email') {
+ // Route to the email queue unless this is a test run: tests execute in-process and
+ // never enqueue, so routing would leave the job unworked.
+ const routeToEmailQueue = invocation.queue !== 'email' && !options?.isTest
+ if (routeToEmailQueue) {
+ result = this.routeEmailToQueue(nextInvocation)
+ } else {
+ // isTest is forwarded so a test send stays out of the email's engagement tracking.
+ result = await this.deps.emailService.executeSendEmail(nextInvocation, options?.isTest ?? false)
+ }
+ } else {
+ throw new Error(`Unknown queue type: ${queueParamsType}`)
+ }
+ } else {
+ // Finish execution, carrying forward previous execResult
+ // Tricky: We don't pass metrics in previousResult as they're accumulated in the local metrics array
+ const { metrics: _m, logs: _l, ...previousResultWithoutMetrics } = result || {}
+ result = await this.execute(nextInvocation, options, previousResultWithoutMetrics)
+ }
+
+ logs.push(...result.logs)
+ metrics.push(...result.metrics)
+
+ // If we have finished _or_ something has been scheduled to run later _or_ the job was routed to a different queue then we break the loop
+ if (result.finished || result.invocation.queueScheduledAt || result.invocation.queue !== invocation.queue) {
+ break
+ }
+ }
+
+ if (result.finished) {
+ const capturedAt = invocation.state.globals.event?.captured_at
+ if (capturedAt) {
+ const e2eLagMs = Date.now() - new Date(capturedAt).getTime()
+ destinationE2eLagMsSummary.observe(e2eLagMs)
+ }
+ }
+
+ result.logs = logs
+ result.metrics = metrics
+
+ return result
+ }
+
+ /**
+ * A single Hog step with async functions available: the program can call `fetch`, `sendEmail`
+ * and friends, and its handler leaves the queue parameters the resumed run needs.
+ */
+ async execute(
+ invocation: CyclotronJobInvocationHogFunction,
+ options: HogExecutorExecuteOptions = {},
+ previousResult: HogExecutorPreviousResult = {}
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
+ return this.hogExecutor.execute(
+ invocation,
+ {
+ ...options,
+ asyncFunctionsNames: options.asyncFunctionsNames ?? getRegisteredAsyncFunctionNames(),
+ functions: {
+ generateMessagingPreferencesUrl: (identifier): string | null => {
+ return identifier && typeof identifier === 'string'
+ ? this.deps.recipientTokensService.generatePreferencesUrl({
+ team_id: invocation.teamId,
+ identifier,
+ })
+ : null
+ },
+ ...options.functions,
+ },
+ onAsyncFunction: async ({ name, args, globals }, result) => {
+ const handler = getAsyncFunctionHandler(name)
+ if (!handler) {
+ throw new Error(`Unknown async function '${name}'`)
+ }
+ // Async handlers are responsible for ensuring the resumed VM stack contains
+ // their return value before it next runs - either by pushing directly onto
+ // result.invocation.state.vmState.stack (synchronous handlers) or by deferring
+ // the push to executeFetch / executeSendEmail (queueing handlers). See the
+ // RETURN-VALUE CONTRACT comment in cdp/async-functions/example.ts.
+ await handler.execute(
+ args,
+ {
+ invocation: result.invocation,
+ globals,
+ teamManager: this.deps.teamManager,
+ siteUrl: this.config.siteUrl,
+ },
+ result
+ )
+ },
+ },
+ previousResult
+ )
+ }
+
+ /**
+ * Routes an email send to the dedicated email queue instead of sending inline.
+ * The email worker will pick this up, send via SES, and return the job to the
+ * original queue so the workflow can continue.
+ */
+ private routeEmailToQueue(
+ invocation: CyclotronJobInvocationHogFunction
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
+ const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
+ invocation,
+ {
+ queue: 'email',
+ queueParameters: invocation.queueParameters,
+ queueMetadata: {
+ ...invocation.queueMetadata,
+ originQueue: invocation.queue,
+ },
+ },
+ { finished: false }
+ )
+
+ result.metrics.push({
+ team_id: invocation.teamId,
+ app_source_id: invocation.parentRunId ?? invocation.functionId,
+ instance_id: invocation.state.actionId || invocation.id,
+ metric_kind: 'email',
+ metric_name: 'email_queued',
+ count: 1,
+ })
+
+ cdpEmailQueuedTotal.inc()
+
+ return result
+ }
+
+ private routeToQueue(
+ invocation: CyclotronJobInvocationHogFunction,
+ targetQueue: string
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
+ return createInvocationResult<CyclotronJobInvocationHogFunction>(
+ invocation,
+ {
+ queue: targetQueue as CyclotronJobInvocationHogFunction['queue'],
+ queueParameters: invocation.queueParameters,
+ queueMetadata: undefined,
+ },
+ { finished: false }
+ )
+ }
+
+ @instrumented('hog-executor.executeFetch')
+ async executeFetch(
+ invocation: CyclotronJobInvocationHogFunction,
+ options?: Pick<HogExecutorExecuteAsyncOptions, 'maxFetchRetries'>
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
+ const templateId = invocation.hogFunction.template_id ?? 'unknown'
+ if (invocation.queueParameters?.type !== 'fetch') {
+ throw new Error('Bad invocation')
+ }
+
+ const params = invocation.queueParameters
+
+ const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
+ invocation,
+ {},
+ {
+ finished: false,
+ }
+ )
+ const addLog = createAddLogFunction(result.logs)
+
+ const method = params.method.toUpperCase()
+ let headers = params.headers ?? {}
+
+ if (params.url.startsWith('https://googleads.googleapis.com/') && !headers['developer-token']) {
+ headers['developer-token'] = this.config.googleAdwordsDeveloperToken
+ }
+
+ const integrationInputs = await this.deps.hogInputsService.loadIntegrationInputs(invocation.hogFunction)
+
+ if (Object.keys(integrationInputs).length > 0) {
+ for (const [key, value] of Object.entries(integrationInputs)) {
+ const inputValue = value.value
+ // integration_multi inputs resolve to an array of integrations (e.g. push channels)
+ // and don't participate in the single access-token placeholder substitution below.
+ if (Array.isArray(inputValue) || !inputValue) {
+ continue
+ }
+ const accessToken: string = inputValue.access_token_raw
+ if (!accessToken) {
+ continue
+ }
+
+ const placeholder: string = ACCESS_TOKEN_PLACEHOLDER + invocation.hogFunction.inputs?.[key]?.value
+
+ if (placeholder && accessToken) {
+ const replace = (val: string) => val.replaceAll(placeholder, accessToken)
+
+ params.body = params.body ? replace(params.body) : params.body
+ headers = Object.fromEntries(
+ Object.entries(params.headers ?? {}).map(([key, value]) => [key, replace(value)])
+ )
+ params.url = replace(params.url)
+ }
+ }
+ }
+
+ // Bound event-forwarding loops: a fetch back into this project's own ingestion
+ // endpoint re-enters the pipeline and can re-trigger this same function. The
+ // ingest-URL check gates the team lookup so external fetches (the common case) pay
+ // nothing, and the whole block fails open - the guard must never break a destination
+ // it was only meant to protect.
+ if (isPostHogIngestUrl(params.url)) {
+ try {
+ const team = await this.deps.teamManager.getTeam(invocation.teamId)
+ if (team && isSelfReferentialIngestFetch({ url: params.url, body: params.body, team })) {
+ // Depth is counted per function id, so this destination is bounded only
+ // by how many times IT has re-fed itself - an event that merely passed
+ // through other functions can never trip the guard for it.
+ const functionId = invocation.hogFunction.id
+ const depth = getSelfLoopDepth(invocation.state.globals.event?.properties, functionId)
+
+ if (depth >= SELF_LOOP_MAX_DEPTH) {
+ // This destination has re-fed itself to the cap - break it.
+ selfLoopGuardCounter.inc({ mode: 'enforce', action: 'blocked' })
+ addLog(
+ 'error',
+ `Refusing to fetch a PostHog ingestion endpoint using this project's own API key - this destination's event-forwarding loop has already repeated ${SELF_LOOP_MAX_DEPTH} times. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`
+ )
+ result.error = new Error('Self-referential event-forwarding loop blocked at max depth')
+ result.finished = true
+ return result
+ }
+ // Under the cap - stamp this destination's next hop and proceed.
+ selfLoopGuardCounter.inc({ mode: 'enforce', action: 'allowed_with_counter' })
+ params.body = injectSelfLoopDepth(params.body, functionId, depth + 1)
+ }
+ } catch (err) {
+ logger.warn('🦔', '[HogExecutor] Self-loop guard skipped due to an internal error', {
+ error: err,
+ teamId: invocation.teamId,
+ })
+ }
+ }
+
+ // AWS SigV4 signatures expire after ~5 minutes. Sign immediately before the
+ // fetch (every attempt — including retries) so a request that sat in the
+ // backoff queue or whose first attempt timed out cannot reach AWS with a
+ // stale signature. Signing artifacts (Authorization, X-Amz-Date) are
+ // regenerated here and never persisted back to queueParameters. Credential
+ // resolution + missing-input handling live in `aws-sigv4.ts` — see
+ // `resolveAwsSigV4Credentials` for the encrypted_inputs/inputs lookup order.
+ let signedHeaders = headers
+ if (params.aws_sigv4) {
+ const resolved = resolveAwsSigV4Credentials(params.aws_sigv4, invocation.hogFunction)
+ if (!resolved.ok) {
+ addLog('error', resolved.error)
+ result.error = new Error(resolved.error)
+ result.finished = true
+ return result
+ }
+ signedHeaders = signAwsRequest({
+ method,
+ url: params.url,
+ body: params.body ?? '',
+ headers,
+ credentials: resolved.credentials,
+ })
+ }
+
+ const fetchParams: FetchOptions = { method, headers: signedHeaders }
+
+ if (!['GET', 'HEAD'].includes(method) && params.body) {
+ fetchParams.body = params.body
+ }
+
+ const { fetchError, fetchResponse, fetchDuration } = await cdpTrackedFetch({
+ url: params.url,
+ fetchParams,
+ templateId,
+ teamId: invocation.teamId,
+ hogFunctionId: invocation.hogFunction.id,
+ })
+
+ result.invocation.state.timings.push({
+ kind: 'async_function',
+ duration_ms: fetchDuration,
+ })
+
+ result.invocation.state.attempts++
+
+ if (!fetchResponse || (fetchResponse?.status && fetchResponse.status >= 400)) {
+ const nonFailureSchemaEntry = invocation.hogFunction.inputs_schema?.find(
+ (s) => s.type === 'non_failure_status_codes'
+ )
+ const nonFailureConfig = nonFailureSchemaEntry
+ ? (invocation.hogFunction.inputs?.[nonFailureSchemaEntry.key]?.value as
+ | Array<number | string>
+ | null
+ | undefined)
+ : undefined
+ const isNonFailure = isNonFailureStatus(fetchResponse?.status, nonFailureConfig)
+
+ const backoffMs = Math.min(
+ this.config.fetchBackoffBaseMs * result.invocation.state.attempts +
+ Math.floor(Math.random() * this.config.fetchBackoffBaseMs),
+ this.config.fetchBackoffMaxMs
+ )
+
+ const canRetry = isFetchResponseRetriable(fetchResponse, fetchError)
+
+ let message = `HTTP fetch failed on attempt ${result.invocation.state.attempts} with status code ${
+ fetchResponse?.status ?? '(none)'
+ }.`
+
+ if (fetchError) {
+ message += ` Error: ${fetchError.message}.`
+ }
+
+ if (canRetry) {
+ message += ` Retrying in ${backoffMs}ms.`
+ }
+
+ addLog(isNonFailure ? 'info' : 'error', message)
+
+ const maxRetries = options?.maxFetchRetries ?? this.config.fetchRetries
+ if (canRetry && result.invocation.state.attempts < maxRetries) {
+ await fetchResponse?.dump()
+ result.invocation.queueParameters = params
+ result.invocation.queuePriority = invocation.queuePriority + 1
+ result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: backoffMs })
+
+ return result
+ } else if (!isNonFailure) {
+ result.error = new Error(message)
+ }
+ }
+
+ // Reset the attempts as we are done
+ result.invocation.state.attempts = 0
+
+ let body: unknown = undefined
+ try {
+ body = await fetchResponse?.text()
+
+ if (typeof body === 'string') {
+ try {
+ body = parseJSON(body)
+ } catch {
+ // Pass through the error
+ }
+ }
+ } catch (e) {
+ addLog('error', `Failed to parse response body: ${e.message}`)
+ body = undefined
+ }
+
+ // Keep the status 500 fallback so template guards like `if (res.status
+ // >= 400) throw` still fire on a client-side abort and prevent
+ // subsequent fetches in multi-step templates from running against
+ // broken assumptions. Populate body with the real client-side error
+ // name and message so the terminal log stops reading as "status 500"
+ // with an empty body and instead tells the customer what actually
+ // happened (connect timeout, socket abort, DNS failure, etc.).
+ const hogVmResponse: {
+ status: number
+ body: unknown
+ } = {
+ status: fetchResponse?.status ?? 500,
+ body: body ?? (fetchError ? `${fetchError.name}: ${fetchError.message}` : undefined),
+ }
+
+ // Finally we create the response object as the VM expects
+ result.invocation.state.vmState!.stack.push(hogVmResponse)
+ result.execResult = hogVmResponse
+
+ result.metrics.push({
+ team_id: invocation.teamId,
+ app_source_id: invocation.parentRunId ?? invocation.functionId,
+ metric_kind: 'other',
+ metric_name: 'fetch',
+ count: 1,
+ })
+
+ return result
+ }
+}
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 6e92e1cdab5b..b5e34488354a 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -6,6 +6,7 @@ import { AddressInfo } from 'net'
import { CyclotronInvocationQueueParametersFetchType } from '~/cdp/schema/cyclotron'
import { logger } from '~/common/utils/logger'
+import { HogExecutorAsyncService } from '../../../src/cdp/services/hog-executor-async.service'
import { HogExecutorService } from '../../../src/cdp/services/hog-executor.service'
import { HogInputsService } from '../../../src/cdp/services/hog-inputs.service'
import { RecipientsManagerService } from '../../../src/cdp/services/managers/recipients-manager.service'
@@ -25,7 +26,8 @@ import { promisifyCallback } from '~/common/utils/utils'
import { compileHog } from '../templates/compiler'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
-import { EXTEND_OBJECT_KEY, isConnectionLevelError } from './hog-executor.service'
+import { isConnectionLevelError } from '../utils/cdp-fetch'
+import { EXTEND_OBJECT_KEY } from './hog-inputs.service'
import { SELF_LOOP_DEPTH_PROPERTY, selfLoopGuardCounter } from './self-loop-guard'
// Mock before importing fetch
@@ -50,7 +52,7 @@ const cleanLogs = (logs: string[]): string[] => {
describe('Hog Executor', () => {
jest.setTimeout(1000)
- let executor: HogExecutorService
+ let executor: HogExecutorAsyncService
let hub: Hub
beforeEach(async () => {
@@ -82,19 +84,23 @@ describe('Hog Executor', () => {
new RecipientsManagerService(hub.postgres)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
- executor = new HogExecutorService(
+ executor = new HogExecutorAsyncService(
+ new HogExecutorService({ executionTimeoutMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS }, hogInputsService),
{
- hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ siteUrl: hub.SITE_URL,
},
- { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- undefined as any
+ {
+ teamManager: hub.teamManager,
+ hogInputsService,
+ emailService,
+ recipientTokensService,
+ // No push sends in this suite - the push queue type is covered by push-notification.service.test.ts
+ pushNotificationService: undefined as any,
+ }
)
})
@@ -115,7 +121,7 @@ describe('Hog Executor', () => {
],
}
- const values = executor.getSensitiveValues(hogFunction, inputs)
+ const values = executor.hogExecutor.getSensitiveValues(hogFunction, inputs)
// Without integration_multi + array handling these secrets leak into team-visible logs.
expect(values).toContain('fcm-secret-token')
@@ -351,311 +357,7 @@ describe('Hog Executor', () => {
})
})
- describe('filtering', () => {
- it('builds the correct globals object when filtering', async () => {
- const fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.no_filters,
- })
-
- const inputGlobals = createHogExecutionGlobals({ groups: {} })
- expect(inputGlobals.source).toBeUndefined()
- const results = await executor.buildHogFunctionInvocations([fn], inputGlobals)
-
- expect(results.invocations).toHaveLength(1)
-
- expect(results.invocations[0].state.globals.source).toEqual({
- name: 'Hog Function',
- url: `http://localhost:8000/projects/1/functions/${fn.id}/configuration/`,
- })
- })
-
- it('can filters incoming messages correctly', async () => {
- const fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.pageview_or_autocapture_filter,
- })
-
- const resultsShouldntMatch = await executor.buildHogFunctionInvocations(
- [fn],
- createHogExecutionGlobals({ groups: {} })
- )
- expect(resultsShouldntMatch.invocations).toHaveLength(0)
- expect(resultsShouldntMatch.metrics).toHaveLength(1)
-
- const resultsShouldMatch = await executor.buildHogFunctionInvocations(
- [fn],
- createHogExecutionGlobals({
- groups: {},
- event: {
- event: '$pageview',
- properties: {
- $current_url: 'https://posthog.com',
- },
- } as any,
- })
- )
- expect(resultsShouldMatch.invocations).toHaveLength(1)
- expect(resultsShouldMatch.metrics).toHaveLength(0)
- })
-
- it('can use elements_chain_texts', async () => {
- const fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.elements_text_filter,
- })
-
- const elementsChain = (buttonText: string) =>
- `span.LemonButton__content:attr__class="LemonButton__content"nth-child="2"nth-of-type="2"text="${buttonText}";span.LemonButton__chrome:attr__class="LemonButton__chrome"nth-child="1"nth-of-type="1";button.LemonButton.LemonButton--has-icon.LemonButton--secondary.LemonButton--status-default:attr__class="LemonButton LemonButton--secondary LemonButton--status-default LemonButton--has-icon"attr__type="button"nth-child="1"nth-of-type="1"text="${buttonText}";div.flex.gap-4.items-center:attr__class="flex gap-4 items-center"nth-child="1"nth-of-type="1";div.flex.flex-wrap.gap-4.justify-between:attr__class="flex gap-4 justify-between flex-wrap"nth-child="3"nth-of-type="3";div.flex.flex-1.flex-col.gap-4.h-full.relative.w-full:attr__class="relative w-full flex flex-col gap-4 flex-1 h-full"nth-child="1"nth-of-type="1";div.LemonTabs__content:attr__class="LemonTabs__content"nth-child="2"nth-of-type="1";div.LemonTabs.LemonTabs--medium:attr__class="LemonTabs LemonTabs--medium"attr__style="--lemon-tabs-slider-width: 48px; --lemon-tabs-slider-offset: 0px;"nth-child="1"nth-of-type="1";div.Navigation3000__scene:attr__class="Navigation3000__scene"nth-child="2"nth-of-type="2";main:nth-child="2"nth-of-type="1";div.Navigation3000:attr__class="Navigation3000"nth-child="1"nth-of-type="1";div:attr__id="root"attr_id="root"nth-child="3"nth-of-type="1";body.overflow-hidden:attr__class="overflow-hidden"attr__theme="light"nth-child="2"nth-of-type="1"`
-
- const hogGlobals1 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('Not our text'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldntMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals1)
- expect(resultsShouldntMatch.invocations).toHaveLength(0)
- expect(resultsShouldntMatch.metrics).toHaveLength(1)
-
- const hogGlobals2 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('Reload'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals2)
- expect(resultsShouldMatch.invocations).toHaveLength(1)
- expect(resultsShouldMatch.metrics).toHaveLength(0)
- })
-
- it('can use elements_chain_href', async () => {
- const fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.elements_href_filter,
- })
-
- const elementsChain = (link: string) =>
- `span.LemonButton__content:attr__class="LemonButton__content"attr__href="${link}"href="${link}"nth-child="2"nth-of-type="2"text="Activity";span.LemonButton__chrome:attr__class="LemonButton__chrome"nth-child="1"nth-of-type="1";a.LemonButton.LemonButton--full-width.LemonButton--has-icon.LemonButton--secondary.LemonButton--status-alt.Link.NavbarButton:attr__class="Link LemonButton LemonButton--secondary LemonButton--status-alt LemonButton--full-width LemonButton--has-icon NavbarButton"attr__data-attr="menu-item-activity"attr__href="${link}"href="${link}"nth-child="1"nth-of-type="1"text="Activity";li.w-full:attr__class="w-full"nth-child="6"nth-of-type="6";ul:nth-child="1"nth-of-type="1";div.Navbar3000__top.ScrollableShadows__inner:attr__class="ScrollableShadows__inner Navbar3000__top"nth-child="1"nth-of-type="1";div.ScrollableShadows.ScrollableShadows--vertical:attr__class="ScrollableShadows ScrollableShadows--vertical"nth-child="1"nth-of-type="1";div.Navbar3000__content:attr__class="Navbar3000__content"nth-child="1"nth-of-type="1";nav.Navbar3000:attr__class="Navbar3000"nth-child="1"nth-of-type="1";div.Navigation3000:attr__class="Navigation3000"nth-child="1"nth-of-type="1";div:attr__id="root"attr_id="root"nth-child="3"nth-of-type="1";body.overflow-hidden:attr__class="overflow-hidden"attr__theme="light"nth-child="2"nth-of-type="1"`
-
- const hogGlobals1 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('/project/1/not-a-link'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldntMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals1)
- expect(resultsShouldntMatch.invocations).toHaveLength(0)
- expect(resultsShouldntMatch.metrics).toHaveLength(1)
-
- const hogGlobals2 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('/project/1/activity/explore'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals2)
- expect(resultsShouldMatch.invocations).toHaveLength(1)
- expect(resultsShouldMatch.metrics).toHaveLength(0)
- })
-
- it('can use elements_chain_tags and _ids', async () => {
- const fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.elements_tag_and_id_filter,
- })
-
- const elementsChain = (id: string) =>
- `a.Link.font-semibold.text-text-3000.text-xl:attr__class="Link font-semibold text-xl text-text-3000"attr__href="/project/1/dashboard/1"attr__id="${id}"attr_id="${id}"href="/project/1/dashboard/1"nth-child="1"nth-of-type="1"text="My App Dashboard";div.ProjectHomepage__dashboardheader__title:attr__class="ProjectHomepage__dashboardheader__title"nth-child="1"nth-of-type="1";div.ProjectHomepage__dashboardheader:attr__class="ProjectHomepage__dashboardheader"nth-child="2"nth-of-type="2";div.ProjectHomepage:attr__class="ProjectHomepage"nth-child="1"nth-of-type="1";div.Navigation3000__scene:attr__class="Navigation3000__scene"nth-child="2"nth-of-type="2";main:nth-child="2"nth-of-type="1";div.Navigation3000:attr__class="Navigation3000"nth-child="1"nth-of-type="1";div:attr__id="root"attr_id="root"nth-child="3"nth-of-type="1";body.overflow-hidden:attr__class="overflow-hidden"attr__theme="light"nth-child="2"nth-of-type="1"`
-
- const hogGlobals1 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('notfound'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldntMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals1)
- expect(resultsShouldntMatch.invocations).toHaveLength(0)
- expect(resultsShouldntMatch.metrics).toHaveLength(1)
-
- const hogGlobals2 = createHogExecutionGlobals({
- groups: {},
- event: {
- uuid: 'uuid',
- event: '$autocapture',
- elements_chain: elementsChain('homelink'),
- distinct_id: 'distinct_id',
- url: 'http://localhost:8000/events/1',
- properties: {
- $lib_version: '1.2.3',
- },
- timestamp: new Date().toISOString(),
- },
- })
-
- const resultsShouldMatch = await executor.buildHogFunctionInvocations([fn], hogGlobals2)
- expect(resultsShouldMatch.invocations).toHaveLength(1)
- expect(resultsShouldMatch.metrics).toHaveLength(0)
- })
- })
-
describe('mappings', () => {
- let fn: HogFunctionType
- beforeEach(() => {
- fn = createHogFunction({
- ...HOG_EXAMPLES.simple_fetch,
- ...HOG_INPUTS_EXAMPLES.simple_fetch,
- ...HOG_FILTERS_EXAMPLES.no_filters,
- mappings: [
- {
- // Filters for pageview or autocapture
- ...HOG_FILTERS_EXAMPLES.pageview_or_autocapture_filter,
- inputs: {
- url: {
- order: 0,
- value: 'https://example.com?q={event.event}',
- bytecode: [
- '_H',
- 1,
- 32,
- 'https://example.com?q=',
- 32,
- 'event',
- 32,
- 'event',
- 1,
- 2,
- 2,
- 'concat',
- 2,
- ],
- },
- },
- },
- {
- // No filters so should match all events
- ...HOG_FILTERS_EXAMPLES.no_filters,
- },
-
- {
- // Broken filters so shouldn't match
- ...HOG_FILTERS_EXAMPLES.broken_filters,
- },
- ],
- })
- })
-
- it('can build mappings', async () => {
- const pageviewGlobals = createHogExecutionGlobals({
- event: {
- event: '$pageview',
- properties: {
- $current_url: 'https://posthog.com',
- },
- } as any,
- })
-
- const results1 = await executor.buildHogFunctionInvocations([fn], pageviewGlobals)
- expect(results1.invocations).toHaveLength(2)
- expect(results1.metrics).toHaveLength(1)
- expect(results1.logs).toHaveLength(1)
- expect(results1.logs[0].message).toMatchInlineSnapshot(
- `"Error filtering event uuid: Invalid HogQL bytecode, stack is empty, can not pop"`
- )
-
- const results2 = await executor.buildHogFunctionInvocations(
- [fn],
- createHogExecutionGlobals({
- event: {
- event: 'test',
- } as any,
- })
- )
- expect(results2.invocations).toHaveLength(1)
- expect(results2.metrics).toHaveLength(2)
- expect(results2.logs).toHaveLength(1)
-
- expect(results2.metrics[0].metric_name).toBe('filtered')
- expect(results2.metrics[1].metric_name).toBe('filtering_failed')
- })
-
- it('generates the correct inputs', async () => {
- const pageviewGlobals = createHogExecutionGlobals({
- event: {
- event: '$pageview',
- properties: {
- $current_url: 'https://posthog.com',
- },
- } as any,
- })
-
- const result = await executor.buildHogFunctionInvocations([fn], pageviewGlobals)
- // First mapping has input overrides that should be applied
- expect(result.invocations[0].state.globals.inputs.headers).toEqual({
- version: 'v=',
- })
- expect(result.invocations[0].state.globals.inputs.url).toMatchInlineSnapshot(
- `"https://example.com?q=$pageview"`
- )
- // Second mapping has no input overrides
- expect(result.invocations[1].state.globals.inputs.headers).toEqual({
- version: 'v=',
- })
- expect(result.invocations[1].state.globals.inputs.url).toMatchInlineSnapshot(
- `"https://example.com/posthog-webhook"`
- )
- })
-
it('rebuilds mapping inputs when an invocation arrives without inputs (rerun path)', async () => {
// The rerun path strips `inputs` from the persisted globals and lets
// the executor rebuild them. For mapping destinations the mapping's
@@ -1843,7 +1545,9 @@ describe('Hog Executor', () => {
},
}
- jest.spyOn(executor['hogInputsService'], 'loadIntegrationInputs').mockResolvedValue(mockIntegrationInputs)
+ jest.spyOn(executor['deps'].hogInputsService, 'loadIntegrationInputs').mockResolvedValue(
+ mockIntegrationInputs
+ )
const invocation = createExampleInvocation()
invocation.state.globals.inputs = mockIntegrationInputs
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index d6ad0ea96be8..2e091ecbcad1 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -1,239 +1,31 @@
import { DateTime } from 'luxon'
-import { Counter, Histogram } from 'prom-client'
+import { Histogram } from 'prom-client'
import { ExecResult, convertHogToJS } from '@posthog/hogvm'
-import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
import { instrumented } from '~/common/tracing/tracing-utils'
-import { fetchAttribution } from '~/common/utils/fetch-attribution'
-import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
-import { FetchOptions, FetchResponse, InvalidRequestError, SecureRequestError, fetch } from '~/common/utils/request'
-import { TeamManager } from '~/common/utils/team-manager'
-import { tryCatch } from '~/common/utils/try-catch'
-import { UUIDT } from '~/common/utils/utils'
-import { PluginsServerConfig } from '../../types'
-import { getAsyncFunctionHandler, getRegisteredAsyncFunctionNames } from '../async-function-registry'
-import '../async-functions'
import type {
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
- HogFunctionFilterGlobals,
HogFunctionInvocationGlobals,
HogFunctionInvocationGlobalsWithInputs,
HogFunctionType,
- LogEntry,
- MinimalAppMetric,
- MinimalLogEntry,
} from '../types'
-import { createAddLogFunction, destinationE2eLagMsSummary, sanitizeLogMessage } from '../utils'
-import { resolveAwsSigV4Credentials, signAwsRequest } from '../utils/aws-sigv4'
+import { createAddLogFunction, sanitizeLogMessage } from '../utils'
import { execHog } from '../utils/hog-exec'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'
-import { createInvocation, createInvocationResult } from '../utils/invocation-utils'
-import { isNonFailureStatus } from '../utils/non-failure-status-codes'
+import { createInvocationResult } from '../utils/invocation-utils'
import { HogInputsService } from './hog-inputs.service'
-import { EmailService } from './messaging/email.service'
-import { PushNotificationService } from './messaging/push-notification.service'
-import { RecipientTokensService } from './messaging/recipient-tokens.service'
-import {
- SELF_LOOP_MAX_DEPTH,
- getSelfLoopDepth,
- injectSelfLoopDepth,
- isPostHogIngestUrl,
- isSelfReferentialIngestFetch,
- selfLoopGuardCounter,
-} from './self-loop-guard'
-
-/** Narrowed config type for CDP fetch retry settings, used by native/segment destination executors */
-export type CdpFetchConfig = Pick<
- PluginsServerConfig,
- 'CDP_FETCH_RETRIES' | 'CDP_FETCH_BACKOFF_BASE_MS' | 'CDP_FETCH_BACKOFF_MAX_MS'
->
export interface HogExecutorConfig {
- hogCostTimingUpperMs: number
- googleAdwordsDeveloperToken: string
- fetchRetries: number
- fetchBackoffBaseMs: number
- fetchBackoffMaxMs: number
-}
-
-export interface HogExecutorAsyncContext {
- teamManager: TeamManager
- siteUrl: string
-}
-
-const cdpEmailQueuedTotal = new Counter({
- name: 'cdp_email_queued_total',
- help: 'Total emails routed to the dedicated email queue',
-})
-
-const cdpHttpRequests = new Counter({
- name: 'cdp_http_requests',
- help: 'HTTP requests and their outcomes',
- labelNames: ['status', 'template_id'],
-})
-
-const cdpHttpRequestTiming = new Histogram({
- name: 'cdp_http_request_timing_ms',
- help: 'Timing of HTTP requests',
- buckets: [0, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000],
-})
-
-const cdpHttpRequestTimingRetried = new Histogram({
- name: 'cdp_http_request_timing_retried_ms',
- help: 'Timing of HTTP requests that required immediate retry after a connection-level error',
- buckets: [0, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000],
-})
-
-// SecureRequestError (private/link-local IP), ResolutionError (DNS failed or every
-// resolved IP was unsafe) and InvalidRequestError (bad scheme/URL) all mean the request
-// was refused before or during connection — never a response from the destination.
-// Matched by name, not instanceof: tests that mock ~/common/utils/request leave the
-// error classes undefined, and instanceof against undefined throws.
-export function isBlockedRequestError(error: unknown): boolean {
- const name = (error as { name?: string } | null)?.name
- return name === 'SecureRequestError' || name === 'ResolutionError' || name === 'InvalidRequestError'
-}
-
-// Emit ops-visible attribution for a blocked request. The low-level guard in
-// common/utils/request.ts increments `node_request_unsafe` but has no team/function context,
-// and the customer-facing `addLog` entries are team-scoped and not queryable from the ops
-// side — this log carries the attribution needed to trace a block back to a destination.
-function logBlockedRequest(
- error: Error,
- { url, templateId, teamId, hogFunctionId }: CdpFetchAttribution & { url: string; templateId: string }
-): void {
- let hostname: string | undefined
- try {
- hostname = new URL(url).hostname
- } catch {
- // Malformed URL (InvalidRequestError) — hostname stays undefined
- }
- logger.warn('[cdpTrackedFetch] Request blocked by SSRF / URL-validation guard', {
- reason: error.name,
- message: error.message,
- hostname,
- teamId,
- hogFunctionId,
- templateId,
- })
-}
-
-// Stale keep-alive connections produce these errors when the server has closed its end before
-// we reuse the socket. A single in-process retry on a fresh connection may resolve them immediately.
-export function isConnectionLevelError(error: any): boolean {
- return (
- error?.code === 'UND_ERR_SOCKET' || // undici SocketError ("other side closed")
- error?.code === 'ECONNRESET' ||
- error?.code === 'EPIPE' ||
- error?.message === 'other side closed' ||
- error?.message === 'socket hang up'
- )
-}
-
-// Attribution for a tracked fetch, so a blocked/refused request can be traced back to the
-// owning hog function and team. Optional because a few callers (push notifications, hog
-// transformations) hand `cdpTrackedFetch` to the Hog VM without an invocation in scope.
-export type CdpFetchAttribution = {
- teamId?: number
- hogFunctionId?: string
-}
-
-export async function cdpTrackedFetch({
- url,
- fetchParams,
- templateId,
- teamId,
- hogFunctionId,
-}: {
- url: string
- fetchParams: FetchOptions
- templateId: string
-} & CdpFetchAttribution): Promise<{
- fetchError: Error | null
- fetchResponse: FetchResponse | null
- fetchDuration: number
-}> {
- const start = performance.now()
-
- // Attribution read by the URL-validation check logs in common/utils/request.ts, which
- // run inside undici's connect flow where no caller context is otherwise available.
- const doFetch = () =>
- fetchAttribution.run({ teamId, hogFunctionId, templateId }, () =>
- tryCatch(async () => await fetch(url, fetchParams))
- )
-
- let [fetchError, fetchResponse] = await doFetch()
-
- const fetchDuration = performance.now() - start
- cdpHttpRequestTiming.observe(fetchDuration)
- cdpHttpRequests.inc({ status: fetchResponse?.status?.toString() ?? 'error', template_id: templateId })
-
- if (fetchError && isConnectionLevelError(fetchError)) {
- logger.warn('🦔', '[cdpTrackedFetch] Connection-level error detected, immediately retrying fetch once', {
- url,
- error: fetchError,
- })
- ;[fetchError, fetchResponse] = await doFetch()
- const retryDuration = performance.now() - start
- cdpHttpRequestTimingRetried.observe(retryDuration)
- cdpHttpRequests.inc({ status: fetchResponse?.status?.toString() ?? 'error', template_id: templateId })
- if (fetchError && isBlockedRequestError(fetchError)) {
- logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })
- }
- return { fetchError, fetchResponse, fetchDuration: retryDuration }
- }
-
- if (fetchError && isBlockedRequestError(fetchError)) {
- logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })
- }
-
- return { fetchError, fetchResponse, fetchDuration }
-}
-
-export const RETRIABLE_STATUS_CODES = [
- 408, // Request Timeout
- 429, // Too Many Requests (rate limiting)
- 500, // Internal Server Error
- 502, // Bad Gateway
- 503, // Service Unavailable
- 504, // Gateway Timeout
-]
-
-function formatNumber(val: number) {
- return Number(val.toPrecision(2)).toString()
-}
-
-export const isFetchResponseRetriable = (response: FetchResponse | null, error: any | null): boolean => {
- let canRetry = !!response?.status && RETRIABLE_STATUS_CODES.includes(response.status)
-
- if (error) {
- if (
- error instanceof SecureRequestError ||
- error instanceof InvalidRequestError ||
- error.name === 'ResponseContentLengthMismatchError'
- ) {
- canRetry = false
- } else {
- canRetry = true // Only retry on general errors, not security, validation, or response parsing errors
- }
- }
-
- return canRetry
-}
-
-export const getNextRetryTime = (backoffBaseMs: number, backoffMaxMs: number, tries: number): DateTime => {
- const backoffMs = Math.min(backoffBaseMs * tries + Math.floor(Math.random() * backoffBaseMs), backoffMaxMs)
- return DateTime.utc().plus({ milliseconds: backoffMs })
+ /** Hard wall-clock limit for one Hog program. The VM aborts the invocation once it elapses. */
+ executionTimeoutMs: number
}
export const MAX_ASYNC_STEPS = 5
export const MAX_HOG_LOGS = 25
-export const EXTEND_OBJECT_KEY = '$$_extend_object'
-export const MAX_FETCH_TIMEOUT_MS = 10000
const hogExecutionDuration = new Histogram({
name: 'cdp_hog_function_execution_duration_ms',
@@ -248,30 +40,48 @@ const hogFunctionStateMemory = new Histogram({
buckets: [0, 50, 100, 250, 500, 1000, 2000, 3000, 5000, Infinity],
})
+function formatNumber(val: number) {
+ return Number(val.toPrecision(2)).toString()
+}
+
+/**
+ * Called when the VM suspends on an async function instead of finishing. The Hog core has no way
+ * to service one, so a caller that wants async functions (fetch, email, push) must supply this -
+ * see HogExecutorAsyncService. Without it a suspending function is an error.
+ */
+export type HogExecutorAsyncFunctionHandler = (
+ call: { name: string; args: any[]; globals: HogFunctionInvocationGlobalsWithInputs },
+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>
+) => Promise<void>
+
+/** The parts of an earlier step's result that carry forward into the next one. */
+export type HogExecutorPreviousResult = Pick<
+ Partial<CyclotronJobInvocationResult>,
+ 'finished' | 'capturedPostHogEvents' | 'warehouseWebhookPayloads' | 'logs' | 'metrics' | 'error' | 'execResult'
+>
+
export type HogExecutorExecuteOptions = {
functions?: Record<string, (args: unknown[]) => unknown>
+ /**
+ * Async functions are stubbed in the VM so the program can call them and suspend. Defaults to
+ * none, meaning any async call is unknown to the VM - callers that can service them pass their
+ * names (and an `onAsyncFunction` handler) in.
+ */
asyncFunctionsNames?: string[]
+ onAsyncFunction?: HogExecutorAsyncFunctionHandler
}
-export type HogExecutorExecuteAsyncOptions = HogExecutorExecuteOptions & {
- maxAsyncFunctions?: number
- maxFetchRetries?: number
- // Set only by the editor's test panel ("Run test"), marking this invocation as a test send. Two
- // effects: emails run inline via EmailService instead of routing to the email queue (the test
- // endpoint executes in-process and never enqueues to cyclotron, so routing would leave the job
- // unworked), and messaging channels skip metrics/assets so a test doesn't pollute the workflow's
- // Metrics and Assets tabs.
- isTest?: boolean
-}
-
+/**
+ * Synchronous Hog execution: build inputs, run the bytecode, collect logs, metrics and timings.
+ *
+ * Deliberately has no fetch, email, push, team or Redis dependency - transformations run in
+ * ingestion on exactly this and must not inherit CDP delivery infrastructure. Anything that needs
+ * to suspend and resume belongs in HogExecutorAsyncService, which wraps this one.
+ */
export class HogExecutorService {
constructor(
private config: HogExecutorConfig,
- private asyncContext: HogExecutorAsyncContext,
- private hogInputsService: HogInputsService,
- private emailService: EmailService,
- private recipientTokensService: RecipientTokensService,
- private pushNotificationService: PushNotificationService
+ private hogInputsService: HogInputsService
) {}
async buildInputsWithGlobals(
@@ -327,279 +137,11 @@ export class HogExecutorService {
return merged
}
- async buildHogFunctionInvocations(
- hogFunctions: HogFunctionType[],
- triggerGlobals: HogFunctionInvocationGlobals
- ): Promise<{
- invocations: CyclotronJobInvocationHogFunction[]
- metrics: MinimalAppMetric[]
- logs: LogEntry[]
- }> {
- const metrics: MinimalAppMetric[] = []
- const logs: LogEntry[] = []
- const invocations: CyclotronJobInvocationHogFunction[] = []
-
- // TRICKY: The frontend generates filters matching the Clickhouse event type so we are converting back
- const filterGlobals = convertToHogFunctionFilterGlobal(triggerGlobals)
-
- const _filterHogFunction = async (
- hogFunction: HogFunctionType,
- filters: HogFunctionType['filters'],
- filterGlobals: HogFunctionFilterGlobals
- ): Promise<boolean> => {
- const filterResults = await filterFunctionInstrumented({
- fn: hogFunction,
- filters,
- filterGlobals,
- })
-
- // Add any generated metrics and logs to our collections
- metrics.push(...filterResults.metrics)
- logs.push(...filterResults.logs)
-
- return filterResults.match
- }
-
- const _buildInvocation = async (
- hogFunction: HogFunctionType,
- additionalInputs?: HogFunctionType['inputs']
- ): Promise<CyclotronJobInvocationHogFunction | null> => {
- try {
- const globalsWithSource = {
- ...triggerGlobals,
- source: {
- name: hogFunction.name ?? `Hog function: ${hogFunction.id}`,
- url: `${triggerGlobals.project.url}/functions/${hogFunction.id}/configuration/`,
- },
- }
-
- const globalsWithInputs = await this.hogInputsService.buildInputsWithGlobals(
- hogFunction,
- globalsWithSource,
- additionalInputs
- )
-
- return createInvocation(globalsWithInputs, hogFunction)
- } catch (error) {
- logs.push({
- team_id: hogFunction.team_id,
- log_source: 'hog_function',
- log_source_id: hogFunction.id,
- instance_id: new UUIDT().toString(), // random UUID, like it would be for an invocation
- timestamp: DateTime.now(),
- level: 'error',
- message: `Error building inputs for event ${triggerGlobals.event.uuid}: ${error.message}`,
- })
-
- metrics.push({
- team_id: hogFunction.team_id,
- app_source_id: hogFunction.id,
- metric_kind: 'failure',
- metric_name: 'inputs_failed',
- count: 1,
- })
-
- return null
- }
- }
-
- await Promise.all(
- hogFunctions.map(async (hogFunction) => {
- // We always check the top level filters
- if (!(await _filterHogFunction(hogFunction, hogFunction.filters, filterGlobals))) {
- return
- }
-
- // Check for non-mapping functions first
- if (!hogFunction.mappings) {
- const invocation = await _buildInvocation(hogFunction)
- if (!invocation) {
- return
- }
-
- invocations.push(invocation)
- return
- }
-
- await Promise.all(
- hogFunction.mappings.map(async (mapping) => {
- if (!(await _filterHogFunction(hogFunction, mapping.filters, filterGlobals))) {
- return
- }
-
- const invocation = await _buildInvocation(hogFunction, mapping.inputs ?? {})
- if (!invocation) {
- return
- }
-
- invocations.push(invocation)
- })
- )
- })
- )
-
- return {
- invocations,
- metrics,
- logs,
- }
- }
-
- @instrumented('hog-executor.executeWithAsyncFunctions')
- async executeWithAsyncFunctions(
- invocation: CyclotronJobInvocationHogFunction,
- options?: HogExecutorExecuteAsyncOptions
- ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
- let asyncFunctionCount = 0
- const maxAsyncFunctions = options?.maxAsyncFunctions ?? 1
-
- let result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null = null
- const metrics: MinimalAppMetric[] = []
- const logs: MinimalLogEntry[] = []
-
- while (!result || !result.finished) {
- const nextInvocation: CyclotronJobInvocationHogFunction = result?.invocation ?? invocation
-
- const queueParamsType = nextInvocation.queueParameters?.type
- if (['fetch', 'sendPushNotification', 'email'].includes(queueParamsType ?? '')) {
- asyncFunctionCount++
-
- if (result && asyncFunctionCount > maxAsyncFunctions) {
- // We don't want to block the consumer too much hence we have a limit on async functions
- logger.debug('🦔', `[HogExecutor] Max async functions reached: ${maxAsyncFunctions}`)
- break
- }
-
- // Queue-aware routing: each worker can execute some actions inline
- // and routes others to a specialized queue. The email worker sends
- // emails inline but routes fetches back to hogflow. The hogflow
- // worker does fetches inline but routes emails to the email queue.
- //
- // Future: once we add an execution time budget, the email worker
- // will also handle fetches inline. The only reason to reschedule
- // back to hogflow will be when overall execution time exceeds the
- // budget, to avoid blocking the queue.
- if (queueParamsType === 'fetch') {
- if (invocation.queue === 'email') {
- result = this.routeToQueue(
- nextInvocation,
- nextInvocation.queueMetadata?.originQueue ?? 'hogflow'
- )
- } else {
- result = await this.executeFetch(nextInvocation, options)
- }
- } else if (queueParamsType === 'sendPushNotification') {
- result = await this.pushNotificationService.executeSendPushNotification(
- nextInvocation,
- options?.isTest ?? false
- )
- } else if (queueParamsType === 'email') {
- // Route to the email queue unless this is a test run: tests execute in-process and
- // never enqueue, so routing would leave the job unworked.
- const routeToEmailQueue = invocation.queue !== 'email' && !options?.isTest
- if (routeToEmailQueue) {
- result = this.routeEmailToQueue(nextInvocation)
- } else {
- // isTest is forwarded so a test send stays out of the email's engagement tracking.
- result = await this.emailService.executeSendEmail(nextInvocation, options?.isTest ?? false)
- }
- } else {
- throw new Error(`Unknown queue type: ${queueParamsType}`)
- }
- } else {
- // Finish execution, carrying forward previous execResult
- // Tricky: We don't pass metrics in previousResult as they're accumulated in the local metrics array
- const { metrics: _m, logs: _l, ...previousResultWithoutMetrics } = result || {}
- result = await this.execute(nextInvocation, options, previousResultWithoutMetrics)
- }
-
- logs.push(...result.logs)
- metrics.push(...result.metrics)
-
- // If we have finished _or_ something has been scheduled to run later _or_ the job was routed to a different queue then we break the loop
- if (result.finished || result.invocation.queueScheduledAt || result.invocation.queue !== invocation.queue) {
- break
- }
- }
-
- if (result.finished) {
- const capturedAt = invocation.state.globals.event?.captured_at
- if (capturedAt) {
- const e2eLagMs = Date.now() - new Date(capturedAt).getTime()
- destinationE2eLagMsSummary.observe(e2eLagMs)
- }
- }
-
- result.logs = logs
- result.metrics = metrics
-
- return result
- }
-
- /**
- * Routes an email send to the dedicated email queue instead of sending inline.
- * The email worker will pick this up, send via SES, and return the job to the
- * original queue so the workflow can continue.
- */
- private routeEmailToQueue(
- invocation: CyclotronJobInvocationHogFunction
- ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
- const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
- invocation,
- {
- queue: 'email',
- queueParameters: invocation.queueParameters,
- queueMetadata: {
- ...invocation.queueMetadata,
- originQueue: invocation.queue,
- },
- },
- { finished: false }
- )
-
- result.metrics.push({
- team_id: invocation.teamId,
- app_source_id: invocation.parentRunId ?? invocation.functionId,
- instance_id: invocation.state.actionId || invocation.id,
- metric_kind: 'email',
- metric_name: 'email_queued',
- count: 1,
- })
-
- cdpEmailQueuedTotal.inc()
-
- return result
- }
-
- private routeToQueue(
- invocation: CyclotronJobInvocationHogFunction,
- targetQueue: string
- ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> {
- return createInvocationResult<CyclotronJobInvocationHogFunction>(
- invocation,
- {
- queue: targetQueue as CyclotronJobInvocationHogFunction['queue'],
- queueParameters: invocation.queueParameters,
- queueMetadata: undefined,
- },
- { finished: false }
- )
- }
-
@instrumented({ key: 'hog-executor.execute', sendException: false })
async execute(
invocation: CyclotronJobInvocationHogFunction,
options: HogExecutorExecuteOptions = {},
- previousResult: Pick<
- Partial<CyclotronJobInvocationResult>,
- | 'finished'
- | 'capturedPostHogEvents'
- | 'warehouseWebhookPayloads'
- | 'logs'
- | 'metrics'
- | 'error'
- | 'execResult'
- > = {}
+ previousResult: HogExecutorPreviousResult = {}
): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
const loggingContext = {
invocationId: invocation.id,
@@ -653,8 +195,7 @@ export class HogExecutorService {
try {
let hogLogs = 0
- const asyncFunctionsNames = options.asyncFunctionsNames ?? getRegisteredAsyncFunctionNames()
- const asyncFunctions = asyncFunctionsNames.reduce(
+ const asyncFunctions = (options.asyncFunctionsNames ?? []).reduce(
(acc, fn) => {
acc[fn] = async () => Promise.resolve()
return acc
@@ -664,7 +205,7 @@ export class HogExecutorService {
const execHogOutcome = await execHog(invocationInput, {
globals,
- timeout: this.config.hogCostTimingUpperMs,
+ timeout: this.config.executionTimeoutMs,
maxAsyncSteps: MAX_ASYNC_STEPS, // NOTE: This will likely be configurable in the future
asyncFunctions: asyncFunctions,
functions: {
@@ -687,14 +228,6 @@ export class HogExecutorService {
message: sanitizeLogMessage(args, sensitiveValues),
})
},
- generateMessagingPreferencesUrl: (identifier): string | null => {
- return identifier && typeof identifier === 'string'
- ? this.recipientTokensService.generatePreferencesUrl({
- team_id: invocation.teamId,
- identifier,
- })
- : null
- },
postHogCapture: (event) => {
const distinctId = event.distinct_id || globals.event?.distinct_id || globals.person?.id
const eventName = event.event
@@ -778,20 +311,12 @@ export class HogExecutorService {
}
if (execRes.asyncFunctionName) {
- const handler = getAsyncFunctionHandler(execRes.asyncFunctionName)
- if (!handler) {
- throw new Error(`Unknown async function '${execRes.asyncFunctionName}'`)
+ if (!options.onAsyncFunction) {
+ throw new Error(
+ `Function suspended on async function '${execRes.asyncFunctionName}' but this executor cannot run async functions`
+ )
}
- // Async handlers are responsible for ensuring the resumed VM stack contains
- // their return value before it next runs - either by pushing directly onto
- // result.invocation.state.vmState.stack (synchronous handlers) or by deferring
- // the push to executeFetch / executeSendEmail (queueing handlers). See the
- // RETURN-VALUE CONTRACT comment in cdp/async-functions/example.ts.
- await handler.execute(
- args,
- { invocation: result.invocation, globals, ...this.asyncContext },
- result
- )
+ await options.onAsyncFunction({ name: execRes.asyncFunctionName, args, globals }, result)
} else {
addLog('warn', `Function was not finished but also had no async function to execute.`)
}
@@ -830,243 +355,6 @@ export class HogExecutorService {
return result
}
- @instrumented('hog-executor.executeFetch')
- async executeFetch(
- invocation: CyclotronJobInvocationHogFunction,
- options?: Pick<HogExecutorExecuteAsyncOptions, 'maxFetchRetries'>
- ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
- const templateId = invocation.hogFunction.template_id ?? 'unknown'
- if (invocation.queueParameters?.type !== 'fetch') {
- throw new Error('Bad invocation')
- }
-
- const params = invocation.queueParameters
-
- const result = createInvocationResult<CyclotronJobInvocationHogFunction>(
- invocation,
- {},
- {
- finished: false,
- }
- )
- const addLog = createAddLogFunction(result.logs)
-
- const method = params.method.toUpperCase()
- let headers = params.headers ?? {}
-
- if (params.url.startsWith('https://googleads.googleapis.com/') && !headers['developer-token']) {
- headers['developer-token'] = this.config.googleAdwordsDeveloperToken
- }
-
- const integrationInputs = await this.hogInputsService.loadIntegrationInputs(invocation.hogFunction)
-
- if (Object.keys(integrationInputs).length > 0) {
- for (const [key, value] of Object.entries(integrationInputs)) {
- const inputValue = value.value
- // integration_multi inputs resolve to an array of integrations (e.g. push channels)
- // and don't participate in the single access-token placeholder substitution below.
- if (Array.isArray(inputValue) || !inputValue) {
- continue
- }
- const accessToken: string = inputValue.access_token_raw
- if (!accessToken) {
- continue
- }
-
- const placeholder: string = ACCESS_TOKEN_PLACEHOLDER + invocation.hogFunction.inputs?.[key]?.value
-
- if (placeholder && accessToken) {
- const replace = (val: string) => val.replaceAll(placeholder, accessToken)
-
- params.body = params.body ? replace(params.body) : params.body
- headers = Object.fromEntries(
- Object.entries(params.headers ?? {}).map(([key, value]) => [key, replace(value)])
- )
- params.url = replace(params.url)
- }
- }
- }
-
- // Bound event-forwarding loops: a fetch back into this project's own ingestion
- // endpoint re-enters the pipeline and can re-trigger this same function. The
- // ingest-URL check gates the team lookup so external fetches (the common case) pay
- // nothing, and the whole block fails open - the guard must never break a destination
- // it was only meant to protect.
- if (isPostHogIngestUrl(params.url)) {
- try {
- const team = await this.asyncContext.teamManager.getTeam(invocation.teamId)
- if (team && isSelfReferentialIngestFetch({ url: params.url, body: params.body, team })) {
- // Depth is counted per function id, so this destination is bounded only
- // by how many times IT has re-fed itself - an event that merely passed
- // through other functions can never trip the guard for it.
- const functionId = invocation.hogFunction.id
- const depth = getSelfLoopDepth(invocation.state.globals.event?.properties, functionId)
-
- if (depth >= SELF_LOOP_MAX_DEPTH) {
- // This destination has re-fed itself to the cap - break it.
- selfLoopGuardCounter.inc({ mode: 'enforce', action: 'blocked' })
- addLog(
- 'error',
- `Refusing to fetch a PostHog ingestion endpoint using this project's own API key - this destination's event-forwarding loop has already repeated ${SELF_LOOP_MAX_DEPTH} times. To capture an event back into this project use the 'postHogCapture' helper, or to enrich incoming events use a transformation.`
- )
- result.error = new Error('Self-referential event-forwarding loop blocked at max depth')
- result.finished = true
- return result
- }
- // Under the cap - stamp this destination's next hop and proceed.
- selfLoopGuardCounter.inc({ mode: 'enforce', action: 'allowed_with_counter' })
- params.body = injectSelfLoopDepth(params.body, functionId, depth + 1)
- }
- } catch (err) {
- logger.warn('🦔', '[HogExecutor] Self-loop guard skipped due to an internal error', {
- error: err,
- teamId: invocation.teamId,
- })
- }
- }
-
- // AWS SigV4 signatures expire after ~5 minutes. Sign immediately before the
- // fetch (every attempt — including retries) so a request that sat in the
- // backoff queue or whose first attempt timed out cannot reach AWS with a
- // stale signature. Signing artifacts (Authorization, X-Amz-Date) are
- // regenerated here and never persisted back to queueParameters. Credential
- // resolution + missing-input handling live in `aws-sigv4.ts` — see
- // `resolveAwsSigV4Credentials` for the encrypted_inputs/inputs lookup order.
- let signedHeaders = headers
- if (params.aws_sigv4) {
- const resolved = resolveAwsSigV4Credentials(params.aws_sigv4, invocation.hogFunction)
- if (!resolved.ok) {
- addLog('error', resolved.error)
- result.error = new Error(resolved.error)
- result.finished = true
- return result
- }
- signedHeaders = signAwsRequest({
- method,
- url: params.url,
- body: params.body ?? '',
- headers,
- credentials: resolved.credentials,
- })
- }
-
- const fetchParams: FetchOptions = { method, headers: signedHeaders }
-
- if (!['GET', 'HEAD'].includes(method) && params.body) {
- fetchParams.body = params.body
- }
-
- const { fetchError, fetchResponse, fetchDuration } = await cdpTrackedFetch({
- url: params.url,
- fetchParams,
- templateId,
- teamId: invocation.teamId,
- hogFunctionId: invocation.hogFunction.id,
- })
-
- result.invocation.state.timings.push({
- kind: 'async_function',
- duration_ms: fetchDuration,
- })
-
- result.invocation.state.attempts++
-
- if (!fetchResponse || (fetchResponse?.status && fetchResponse.status >= 400)) {
- const nonFailureSchemaEntry = invocation.hogFunction.inputs_schema?.find(
- (s) => s.type === 'non_failure_status_codes'
- )
- const nonFailureConfig = nonFailureSchemaEntry
- ? (invocation.hogFunction.inputs?.[nonFailureSchemaEntry.key]?.value as
- | Array<number | string>
- | null
- | undefined)
- : undefined
- const isNonFailure = isNonFailureStatus(fetchResponse?.status, nonFailureConfig)
-
- const backoffMs = Math.min(
- this.config.fetchBackoffBaseMs * result.invocation.state.attempts +
- Math.floor(Math.random() * this.config.fetchBackoffBaseMs),
- this.config.fetchBackoffMaxMs
- )
-
- const canRetry = isFetchResponseRetriable(fetchResponse, fetchError)
-
- let message = `HTTP fetch failed on attempt ${result.invocation.state.attempts} with status code ${
- fetchResponse?.status ?? '(none)'
- }.`
-
- if (fetchError) {
- message += ` Error: ${fetchError.message}.`
- }
-
- if (canRetry) {
- message += ` Retrying in ${backoffMs}ms.`
- }
-
- addLog(isNonFailure ? 'info' : 'error', message)
-
- const maxRetries = options?.maxFetchRetries ?? this.config.fetchRetries
- if (canRetry && result.invocation.state.attempts < maxRetries) {
- await fetchResponse?.dump()
- result.invocation.queueParameters = params
- result.invocation.queuePriority = invocation.queuePriority + 1
- result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: backoffMs })
-
- return result
- } else if (!isNonFailure) {
- result.error = new Error(message)
- }
- }
-
- // Reset the attempts as we are done
- result.invocation.state.attempts = 0
-
- let body: unknown = undefined
- try {
- body = await fetchResponse?.text()
-
- if (typeof body === 'string') {
- try {
- body = parseJSON(body)
- } catch {
- // Pass through the error
- }
- }
- } catch (e) {
- addLog('error', `Failed to parse response body: ${e.message}`)
- body = undefined
- }
-
- // Keep the status 500 fallback so template guards like `if (res.status
- // >= 400) throw` still fire on a client-side abort and prevent
- // subsequent fetches in multi-step templates from running against
- // broken assumptions. Populate body with the real client-side error
- // name and message so the terminal log stops reading as "status 500"
- // with an empty body and instead tells the customer what actually
- // happened (connect timeout, socket abort, DNS failure, etc.).
- const hogVmResponse: {
- status: number
- body: unknown
- } = {
- status: fetchResponse?.status ?? 500,
- body: body ?? (fetchError ? `${fetchError.name}: ${fetchError.message}` : undefined),
- }
-
- // Finally we create the response object as the VM expects
- result.invocation.state.vmState!.stack.push(hogVmResponse)
- result.execResult = hogVmResponse
-
- result.metrics.push({
- team_id: invocation.teamId,
- app_source_id: invocation.parentRunId ?? invocation.functionId,
- metric_kind: 'other',
- metric_name: 'fetch',
- count: 1,
- })
-
- return result
- }
-
getSensitiveValues(hogFunction: HogFunctionType, inputs: Record<string, any>): string[] {
const values: string[] = []
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
index 570557310a10..093d223326d2 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.test.ts
@@ -1,12 +1,17 @@
import { QuotaLimiting } from '../../common/services/quota-limiting.service'
import { CyclotronJobInvocationHogFunction, HogFunctionInvocationGlobals, HogFunctionType } from '../types'
-import { HogExecutorService } from './hog-executor.service'
+import { buildHogFunctionInvocations } from '../utils/invocation-utils'
import { HogFunctionInvocationPipeline } from './hog-function-invocation-pipeline.service'
import { HogFunctionManagerService } from './managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'
import { HogMaskerService } from './monitoring/hog-masker.service'
import { HogWatcherService, HogWatcherState } from './monitoring/hog-watcher.service'
+jest.mock('../utils/invocation-utils', () => ({
+ ...jest.requireActual('../utils/invocation-utils'),
+ buildHogFunctionInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),
+}))
+
// Mock the rate limiter to give us deterministic control
jest.mock('../../common/services/keyed-rate-limiter.service', () => ({
KeyedRateLimiterService: jest.fn().mockImplementation(() => ({
@@ -53,7 +58,7 @@ function makeGlobals(teamId = 1): HogFunctionInvocationGlobals {
describe('HogFunctionInvocationPipeline', () => {
let hogFunctionManager: jest.Mocked<HogFunctionManagerService>
- let hogExecutor: jest.Mocked<HogExecutorService>
+
let hogWatcher: jest.Mocked<HogWatcherService>
let hogMasker: jest.Mocked<HogMaskerService>
let hogFunctionMonitoringService: jest.Mocked<HogFunctionMonitoringService>
@@ -66,10 +71,6 @@ describe('HogFunctionInvocationPipeline', () => {
getHogFunctionsForTeams: jest.fn().mockResolvedValue({}),
} as unknown as jest.Mocked<HogFunctionManagerService>
- hogExecutor = {
- buildHogFunctionInvocations: jest.fn().mockResolvedValue({ invocations: [], metrics: [], logs: [] }),
- } as unknown as jest.Mocked<HogExecutorService>
-
hogWatcher = {
getEffectiveStates: jest.fn().mockResolvedValue({}),
} as unknown as jest.Mocked<HogWatcherService>
@@ -90,7 +91,7 @@ describe('HogFunctionInvocationPipeline', () => {
pipeline = new HogFunctionInvocationPipeline(config, {
hogFunctionManager,
- hogExecutor,
+ hogInputsService: {} as any,
hogWatcher,
hogWatcherMirror: null,
hogMasker,
@@ -120,7 +121,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('returns invocations for matching hog functions and queues triggered + billing metrics', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn, 'evt-uuid-1')
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -143,7 +144,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('drops invocations in disabled watcher state', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.disabled } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -162,7 +163,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('routes degraded invocations to hogoverflow queue when overflow enabled', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.degraded } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
@@ -179,7 +180,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('drops quota-limited invocations', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
quotaLimiting.isTeamQuotaLimited.mockResolvedValue(true)
@@ -195,7 +196,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('drops masked invocations', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: false }]])
hogMasker.filterByMasking.mockResolvedValue({ masked: [inv], notMasked: [] })
@@ -217,7 +218,7 @@ describe('HogFunctionInvocationPipeline', () => {
const fn2 = makeHogFunction({ id: 'fn-2' })
const inv1 = makeInvocation(fn1, 'evt-same')
const inv2 = makeInvocation(fn2, 'evt-same')
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv1, inv2], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv1, inv2], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({
[fn1.id]: { state: HogWatcherState.healthy },
[fn2.id]: { state: HogWatcherState.healthy },
@@ -241,7 +242,7 @@ describe('HogFunctionInvocationPipeline', () => {
it('does not drop rate-limited invocations (monitoring-only)', async () => {
const fn = makeHogFunction()
const inv = makeInvocation(fn)
- hogExecutor.buildHogFunctionInvocations.mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
+ jest.mocked(buildHogFunctionInvocations).mockResolvedValue({ invocations: [inv], metrics: [], logs: [] })
hogWatcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.healthy } } as any)
rateLimitGroupedMock.mockResolvedValue([[null, { isRateLimited: true }]])
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
index 32b284d444b9..108c2b73ac51 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
@@ -15,8 +15,9 @@ import {
HogFunctionTypeType,
MinimalAppMetric,
} from '../types'
+import { buildHogFunctionInvocations } from '../utils/invocation-utils'
import { mirrorCompare } from '../utils/mirror-call'
-import { HogExecutorService } from './hog-executor.service'
+import { HogInputsService } from './hog-inputs.service'
import { HogFunctionManagerService } from './managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'
import { HogMaskerService } from './monitoring/hog-masker.service'
@@ -31,7 +32,7 @@ export interface HogFunctionInvocationPipelineConfig {
export interface HogFunctionInvocationPipelineDeps {
hogFunctionManager: HogFunctionManagerService
- hogExecutor: HogExecutorService
+ hogInputsService: HogInputsService
hogWatcher: HogWatcherService
hogWatcherMirror: HogWatcherService | null
hogMasker: HogMaskerService
@@ -89,7 +90,8 @@ export class HogFunctionInvocationPipeline {
invocationGlobals.map(async (globals) => {
const teamHogFunctions = hogFunctionsByTeam[globals.project.id]
- const { invocations, metrics, logs } = await this.deps.hogExecutor.buildHogFunctionInvocations(
+ const { invocations, metrics, logs } = await buildHogFunctionInvocations(
+ this.deps.hogInputsService,
teamHogFunctions,
globals
)
diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.ts
index e16f6576f16a..597467489957 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.ts
@@ -17,7 +17,7 @@ export const EXTEND_OBJECT_KEY = '$$_extend_object'
export class HogInputsService {
constructor(
private integrationManager: IntegrationManagerService,
- private recipientTokensService: RecipientTokensService,
+ private recipientTokensService: RecipientTokensService | undefined,
private encryptedFields: EncryptedFields
) {}
@@ -61,6 +61,9 @@ export class HogInputsService {
const emailInput = hogFunction.inputs?.[emailInputSchema?.key ?? '']
if (emailInputSchema && emailInput) {
+ if (!this.recipientTokensService) {
+ throw new Error('HogInputsService was constructed without messaging preference URL support')
+ }
// If we have an email value then we template it out to get the email address
const emailValue = await _formatInput(emailInput, emailInputSchema.key)
if (emailValue?.to?.email) {
diff --git a/nodejs/src/cdp/services/hogflows/actions/action.interface.ts b/nodejs/src/cdp/services/hogflows/actions/action.interface.ts
index 877244e368d8..de639ca267b6 100644
--- a/nodejs/src/cdp/services/hogflows/actions/action.interface.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/action.interface.ts
@@ -3,7 +3,7 @@ import { DateTime } from 'luxon'
import { HogFlowAction } from '~/cdp/schema/hogflow'
import { CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '../../../types'
-import { HogExecutorExecuteAsyncOptions } from '../../hog-executor.service'
+import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'
export interface ActionHandlerResult {
nextAction?: HogFlowAction
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index e278ecde7d25..fead0331f932 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -12,6 +12,7 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, Team } from '~/types'
import { CyclotronJobInvocationHogFlow, DBHogFunctionTemplate } from '../../../types'
+import { HogExecutorAsyncService } from '../../hog-executor-async.service'
import { HogExecutorService } from '../../hog-executor.service'
import { HogInputsService } from '../../hog-inputs.service'
import { HogFunctionTemplateManagerService } from '../../managers/hog-function-template-manager.service'
@@ -31,7 +32,7 @@ describe('HogFunctionHandler', () => {
let hub: Hub
let team: Team
let hogFunctionHandler: HogFunctionHandler
- let mockHogFunctionExecutor: HogExecutorService
+ let mockHogFunctionExecutor: HogExecutorAsyncService
let mockHogFunctionTemplateManager: HogFunctionTemplateManagerService
let mockHogFlowFunctionsService: HogFlowFunctionsService
let mockRecipientPreferencesService: RecipientPreferencesService
@@ -70,19 +71,22 @@ describe('HogFunctionHandler', () => {
new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),
new RecipientsManagerService(hub.postgres)
)
- mockHogFunctionExecutor = new HogExecutorService(
+ mockHogFunctionExecutor = new HogExecutorAsyncService(
+ new HogExecutorService({ executionTimeoutMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS }, hogInputsService),
{
- hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ siteUrl: hub.SITE_URL,
},
- { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- undefined as any
+ {
+ teamManager: hub.teamManager,
+ hogInputsService,
+ emailService,
+ recipientTokensService,
+ pushNotificationService: undefined as any,
+ }
)
mockHogFunctionTemplateManager = new HogFunctionTemplateManagerService(hub.postgres)
mockHogFlowFunctionsService = new HogFlowFunctionsService(
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index e4dfd2bc4200..948dc9cefa44 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -9,7 +9,7 @@ import {
CyclotronJobInvocationResult,
MinimalLogEntry,
} from '../../../types'
-import { HogExecutorExecuteAsyncOptions } from '../../hog-executor.service'
+import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'
import { EmailValidationService } from '../../messaging/email-validation.service'
import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'
import { trackHogFlowBillableInvocation } from '../billing-utils'
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index a5d79a963611..e23303c64aeb 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -14,6 +14,7 @@ import { Hub } from '../../../types'
import { createHub } from '~/common/utils/db/hub'
import { HOG_FILTERS_EXAMPLES } from '../../_tests/examples'
import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'
+import { HogExecutorAsyncService } from '../hog-executor-async.service'
import { HogExecutorService } from '../hog-executor.service'
import { HogInputsService } from '../hog-inputs.service'
import { EmailService } from '../messaging/email.service'
@@ -89,19 +90,22 @@ describe('Hogflow Executor', () => {
new RecipientsManagerService(hub.postgres)
)
const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)
- const hogExecutor = new HogExecutorService(
+ const hogExecutor = new HogExecutorAsyncService(
+ new HogExecutorService({ executionTimeoutMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS }, hogInputsService),
{
- hogCostTimingUpperMs: hub.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
googleAdwordsDeveloperToken: hub.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
fetchRetries: hub.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: hub.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: hub.CDP_FETCH_BACKOFF_MAX_MS,
+ siteUrl: hub.SITE_URL,
},
- { teamManager: hub.teamManager, siteUrl: hub.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- undefined as any
+ {
+ teamManager: hub.teamManager,
+ hogInputsService,
+ emailService,
+ recipientTokensService,
+ pushNotificationService: undefined as any,
+ }
)
const hogFunctionTemplateManager = new HogFunctionTemplateManagerService(hub.postgres)
const hogFlowFunctionsService = new HogFlowFunctionsService(
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 19a0a2140904..fd3ba983eb29 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -21,7 +21,7 @@ import {
} from '../../types'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../../utils/hog-function-filtering'
import { createInvocationResult } from '../../utils/invocation-utils'
-import { HogExecutorExecuteAsyncOptions } from '../hog-executor.service'
+import { HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'
import { EmailValidationService } from '../messaging/email-validation.service'
import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
import { ActionHandler } from './actions/action.interface'
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
index 637bd13a03dd..3cb022b1e020 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
@@ -7,7 +7,7 @@ import {
HogFunctionType,
} from '~/cdp/types'
-import { HogExecutorExecuteAsyncOptions, HogExecutorService } from '../hog-executor.service'
+import { HogExecutorAsyncService, HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'
import { HogFunctionTemplateManagerService } from '../managers/hog-function-template-manager.service'
type FunctionActionType = 'function' | 'function_email' | 'function_sms'
@@ -18,7 +18,7 @@ export class HogFlowFunctionsService {
constructor(
private siteUrl: string,
private hogFunctionTemplateManager: HogFunctionTemplateManagerService,
- private hogFunctionExecutor: HogExecutorService
+ private hogFunctionExecutor: HogExecutorAsyncService
) {}
async buildHogFunction(hogFlow: HogFlow, configuration: Action['config']): Promise<HogFunctionType> {
@@ -110,7 +110,10 @@ export class HogFlowFunctionsService {
...invocation,
hogFunction,
state: invocation.state.currentAction?.hogFunctionState ?? {
- globals: await this.hogFunctionExecutor.buildInputsWithGlobals(hogFunction, globalsWithSource),
+ globals: await this.hogFunctionExecutor.hogExecutor.buildInputsWithGlobals(
+ hogFunction,
+ globalsWithSource
+ ),
timings: [],
attempts: 0,
actionId: invocation.state.currentAction?.id,
diff --git a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts b/nodejs/src/cdp/services/legacy-plugin-executor.service.ts
index 2ddf61097e6c..3aafe3caad8e 100644
--- a/nodejs/src/cdp/services/legacy-plugin-executor.service.ts
+++ b/nodejs/src/cdp/services/legacy-plugin-executor.service.ts
@@ -17,8 +17,8 @@ import {
} from '../legacy-plugins/types'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
import { CDP_TEST_ID, createAddLogFunction, destinationE2eLagMsSummary, isLegacyPluginHogFunction } from '../utils'
+import { cdpTrackedFetch } from '../utils/cdp-fetch'
import { createInvocationResult } from '../utils/invocation-utils'
-import { cdpTrackedFetch } from './hog-executor.service'
const pluginExecutionDuration = new Histogram({
name: 'cdp_plugin_execution_duration_ms',
diff --git a/nodejs/src/cdp/services/native-destination-executor.service.ts b/nodejs/src/cdp/services/native-destination-executor.service.ts
index 9ddf85e8d108..190025683c30 100644
--- a/nodejs/src/cdp/services/native-destination-executor.service.ts
+++ b/nodejs/src/cdp/services/native-destination-executor.service.ts
@@ -8,8 +8,8 @@ import { NATIVE_HOG_FUNCTIONS_BY_ID } from '../templates'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, Response } from '../types'
import { destinationE2eLagMsSummary } from '../utils'
import { CDP_TEST_ID, createAddLogFunction, isNativeHogFunction } from '../utils'
+import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from '../utils/cdp-fetch'
import { createInvocationResult } from '../utils/invocation-utils'
-import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from './hog-executor.service'
const nativeDestinationExecutionDuration = new Histogram({
name: 'cdp_native_execution_duration_ms',
diff --git a/nodejs/src/cdp/services/segment-destination-executor.service.ts b/nodejs/src/cdp/services/segment-destination-executor.service.ts
index 88ebcb879f90..6c5281350521 100644
--- a/nodejs/src/cdp/services/segment-destination-executor.service.ts
+++ b/nodejs/src/cdp/services/segment-destination-executor.service.ts
@@ -9,8 +9,8 @@ import { SEGMENT_DESTINATIONS_BY_ID } from '../segment/segment-templates'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
import { destinationE2eLagMsSummary } from '../utils'
import { CDP_TEST_ID, createAddLogFunction, isSegmentPluginHogFunction } from '../utils'
+import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from '../utils/cdp-fetch'
import { createInvocationResult } from '../utils/invocation-utils'
-import { CdpFetchConfig, cdpTrackedFetch, getNextRetryTime, isFetchResponseRetriable } from './hog-executor.service'
const pluginExecutionDuration = new Histogram({
name: 'cdp_segment_execution_duration_ms',
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index d76d41df2977..bca2ea408375 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -11,6 +11,7 @@ import { defaultConfig } from '~/common/config/config'
import { GeoIPService, GeoIp } from '~/common/utils/geoip'
import { PluginsServerConfig } from '../../../types'
+import { HogExecutorAsyncService } from '../../services/hog-executor-async.service'
import { HogExecutorService } from '../../services/hog-executor.service'
import { HogInputsService } from '../../services/hog-inputs.service'
import { EmailService } from '../../services/messaging/email.service'
@@ -166,7 +167,7 @@ const createGlobals = (
export class TemplateTester {
public template: HogFunctionTemplateCompiled
- private hogExecutor: HogExecutorService
+ private hogExecutor: HogExecutorAsyncService
private nativeExecutor: NativeDestinationExecutorService
private mockHub: PluginsServerConfig
@@ -192,7 +193,7 @@ export class TemplateTester {
this.nativeExecutor = new NativeDestinationExecutorService(defaultConfig)
}
- private createHogExecutor(): HogExecutorService {
+ private createHogExecutor(): HogExecutorAsyncService {
const config = this.mockHub
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
const hogInputsService = new HogInputsService(undefined as any, recipientTokensService, undefined as any)
@@ -214,23 +215,29 @@ export class TemplateTester {
undefined as any,
undefined as any
)
- return new HogExecutorService(
+ return new HogExecutorAsyncService(
+ new HogExecutorService(
+ { executionTimeoutMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS },
+ hogInputsService
+ ),
{
- hogCostTimingUpperMs: config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
googleAdwordsDeveloperToken: config.CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN,
fetchRetries: config.CDP_FETCH_RETRIES,
fetchBackoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
fetchBackoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
+ siteUrl: config.SITE_URL,
},
- { teamManager: this.mockTeamManager as any, siteUrl: config.SITE_URL },
- hogInputsService,
- emailService,
- recipientTokensService,
- undefined as any
+ {
+ teamManager: this.mockTeamManager as any,
+ hogInputsService,
+ emailService,
+ recipientTokensService,
+ pushNotificationService: undefined as any,
+ }
)
}
- private getExecutor(): HogExecutorService | NativeDestinationExecutorService {
+ private getExecutor(): HogExecutorAsyncService | NativeDestinationExecutorService {
return isNativeHogFunction({ template_id: this.template.id }) ? this.nativeExecutor : this.hogExecutor
}
@@ -292,7 +299,7 @@ export class TemplateTester {
template_id: this.template.id,
}
- const globalsWithInputs = await this.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
+ const globalsWithInputs = await this.hogExecutor.hogExecutor.buildInputsWithGlobals(hogFunction, globals)
const invocation = createInvocation(globalsWithInputs, hogFunction)
const transformationFunctions = getTransformationFunctions(this.geoIp!)
const extraFunctions = invocation.hogFunction.type === 'transformation' ? transformationFunctions : {}
@@ -360,7 +367,7 @@ export class TemplateTester {
mappings: [compiledMappingInputs],
}
- const globalsWithInputs = await this.hogExecutor.buildInputsWithGlobals(
+ const globalsWithInputs = await this.hogExecutor.hogExecutor.buildInputsWithGlobals(
hogFunction,
this.createGlobals(_globals),
compiledMappingInputs.inputs
diff --git a/nodejs/src/cdp/utils/cdp-fetch.ts b/nodejs/src/cdp/utils/cdp-fetch.ts
new file mode 100644
index 000000000000..e98af1903b72
--- /dev/null
+++ b/nodejs/src/cdp/utils/cdp-fetch.ts
@@ -0,0 +1,173 @@
+import { DateTime } from 'luxon'
+import { Counter, Histogram } from 'prom-client'
+
+import { fetchAttribution } from '~/common/utils/fetch-attribution'
+import { logger } from '~/common/utils/logger'
+import { FetchOptions, FetchResponse, InvalidRequestError, SecureRequestError, fetch } from '~/common/utils/request'
+import { tryCatch } from '~/common/utils/try-catch'
+
+import { PluginsServerConfig } from '../../types'
+
+export const MAX_FETCH_TIMEOUT_MS = 10000
+
+/** Narrowed config type for CDP fetch retry settings, used by native/segment destination executors */
+export type CdpFetchConfig = Pick<
+ PluginsServerConfig,
+ 'CDP_FETCH_RETRIES' | 'CDP_FETCH_BACKOFF_BASE_MS' | 'CDP_FETCH_BACKOFF_MAX_MS'
+>
+
+const cdpHttpRequests = new Counter({
+ name: 'cdp_http_requests',
+ help: 'HTTP requests and their outcomes',
+ labelNames: ['status', 'template_id'],
+})
+
+const cdpHttpRequestTiming = new Histogram({
+ name: 'cdp_http_request_timing_ms',
+ help: 'Timing of HTTP requests',
+ buckets: [0, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000],
+})
+
+const cdpHttpRequestTimingRetried = new Histogram({
+ name: 'cdp_http_request_timing_retried_ms',
+ help: 'Timing of HTTP requests that required immediate retry after a connection-level error',
+ buckets: [0, 10, 20, 50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000],
+})
+
+// SecureRequestError (private/link-local IP), ResolutionError (DNS failed or every
+// resolved IP was unsafe) and InvalidRequestError (bad scheme/URL) all mean the request
+// was refused before or during connection — never a response from the destination.
+// Matched by name, not instanceof: tests that mock ~/common/utils/request leave the
+// error classes undefined, and instanceof against undefined throws.
+export function isBlockedRequestError(error: unknown): boolean {
+ const name = (error as { name?: string } | null)?.name
+ return name === 'SecureRequestError' || name === 'ResolutionError' || name === 'InvalidRequestError'
+}
+
+// Emit ops-visible attribution for a blocked request. The low-level guard in
+// common/utils/request.ts increments `node_request_unsafe` but has no team/function context,
+// and the customer-facing `addLog` entries are team-scoped and not queryable from the ops
+// side — this log carries the attribution needed to trace a block back to a destination.
+function logBlockedRequest(
+ error: Error,
+ { url, templateId, teamId, hogFunctionId }: CdpFetchAttribution & { url: string; templateId: string }
+): void {
+ let hostname: string | undefined
+ try {
+ hostname = new URL(url).hostname
+ } catch {
+ // Malformed URL (InvalidRequestError) — hostname stays undefined
+ }
+ logger.warn('[cdpTrackedFetch] Request blocked by SSRF / URL-validation guard', {
+ reason: error.name,
+ message: error.message,
+ hostname,
+ teamId,
+ hogFunctionId,
+ templateId,
+ })
+}
+
+// Stale keep-alive connections produce these errors when the server has closed its end before
+// we reuse the socket. A single in-process retry on a fresh connection may resolve them immediately.
+export function isConnectionLevelError(error: any): boolean {
+ return (
+ error?.code === 'UND_ERR_SOCKET' || // undici SocketError ("other side closed")
+ error?.code === 'ECONNRESET' ||
+ error?.code === 'EPIPE' ||
+ error?.message === 'other side closed' ||
+ error?.message === 'socket hang up'
+ )
+}
+
+// Attribution for a tracked fetch, so a blocked/refused request can be traced back to the
+// owning hog function and team. Optional because a few callers (push notifications, hog
+// transformations) hand `cdpTrackedFetch` to the Hog VM without an invocation in scope.
+export type CdpFetchAttribution = {
+ teamId?: number
+ hogFunctionId?: string
+}
+
+export async function cdpTrackedFetch({
+ url,
+ fetchParams,
+ templateId,
+ teamId,
+ hogFunctionId,
+}: {
+ url: string
+ fetchParams: FetchOptions
+ templateId: string
+} & CdpFetchAttribution): Promise<{
+ fetchError: Error | null
+ fetchResponse: FetchResponse | null
+ fetchDuration: number
+}> {
+ const start = performance.now()
+
+ // Attribution read by the URL-validation check logs in common/utils/request.ts, which
+ // run inside undici's connect flow where no caller context is otherwise available.
+ const doFetch = () =>
+ fetchAttribution.run({ teamId, hogFunctionId, templateId }, () =>
+ tryCatch(async () => await fetch(url, fetchParams))
+ )
+
+ let [fetchError, fetchResponse] = await doFetch()
+
+ const fetchDuration = performance.now() - start
+ cdpHttpRequestTiming.observe(fetchDuration)
+ cdpHttpRequests.inc({ status: fetchResponse?.status?.toString() ?? 'error', template_id: templateId })
+
+ if (fetchError && isConnectionLevelError(fetchError)) {
+ logger.warn('🦔', '[cdpTrackedFetch] Connection-level error detected, immediately retrying fetch once', {
+ url,
+ error: fetchError,
+ })
+ ;[fetchError, fetchResponse] = await doFetch()
+ const retryDuration = performance.now() - start
+ cdpHttpRequestTimingRetried.observe(retryDuration)
+ cdpHttpRequests.inc({ status: fetchResponse?.status?.toString() ?? 'error', template_id: templateId })
+ if (fetchError && isBlockedRequestError(fetchError)) {
+ logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })
+ }
+ return { fetchError, fetchResponse, fetchDuration: retryDuration }
+ }
+
+ if (fetchError && isBlockedRequestError(fetchError)) {
+ logBlockedRequest(fetchError, { url, templateId, teamId, hogFunctionId })
+ }
+
+ return { fetchError, fetchResponse, fetchDuration }
+}
+
+export const RETRIABLE_STATUS_CODES = [
+ 408, // Request Timeout
+ 429, // Too Many Requests (rate limiting)
+ 500, // Internal Server Error
+ 502, // Bad Gateway
+ 503, // Service Unavailable
+ 504, // Gateway Timeout
+]
+
+export const isFetchResponseRetriable = (response: FetchResponse | null, error: any | null): boolean => {
+ let canRetry = !!response?.status && RETRIABLE_STATUS_CODES.includes(response.status)
+
+ if (error) {
+ if (
+ error instanceof SecureRequestError ||
+ error instanceof InvalidRequestError ||
+ error.name === 'ResponseContentLengthMismatchError'
+ ) {
+ canRetry = false
+ } else {
+ canRetry = true // Only retry on general errors, not security, validation, or response parsing errors
+ }
+ }
+
+ return canRetry
+}
+
+export const getNextRetryTime = (backoffBaseMs: number, backoffMaxMs: number, tries: number): DateTime => {
+ const backoffMs = Math.min(backoffBaseMs * tries + Math.floor(Math.random() * backoffBaseMs), backoffMaxMs)
+ return DateTime.utc().plus({ milliseconds: backoffMs })
+}
diff --git a/nodejs/src/cdp/utils/invocation-utils.test.ts b/nodejs/src/cdp/utils/invocation-utils.test.ts
index e2aad4c588e6..c9242ddd3cbc 100644
--- a/nodejs/src/cdp/utils/invocation-utils.test.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.test.ts
@@ -2,9 +2,260 @@ import { DateTime } from 'luxon'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import { createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
-import { cloneInvocation, createInvocation } from './invocation-utils'
+import { HogInputsService } from '../services/hog-inputs.service'
+import { buildHogFunctionInvocations, cloneInvocation, createInvocation } from './invocation-utils'
describe('Invocation utils', () => {
+ describe('buildHogFunctionInvocations', () => {
+ // Plain templated inputs only: no integration, email or push_subscription schema types, so
+ // the service never reaches its integration manager, tokens service or encrypted fields.
+ const hogInputsService = new HogInputsService(undefined as any, undefined as any, undefined as any)
+
+ const pageviewGlobals = () =>
+ createHogExecutionGlobals({
+ groups: {},
+ event: { event: '$pageview', properties: { $current_url: 'https://posthog.com' } } as any,
+ })
+
+ it('injects the invoked function as the globals source', async () => {
+ const fn = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+
+ const globals = createHogExecutionGlobals({ groups: {} })
+ expect(globals.source).toBeUndefined()
+
+ const { invocations } = await buildHogFunctionInvocations(hogInputsService, [fn], globals)
+
+ expect(invocations).toHaveLength(1)
+ expect(invocations[0].state.globals.source).toEqual({
+ name: 'Hog Function',
+ url: `http://localhost:8000/projects/1/functions/${fn.id}/configuration/`,
+ })
+ })
+
+ it('builds an invocation only when the filters match, counting a filtered metric otherwise', async () => {
+ const fn = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.pageview_or_autocapture_filter,
+ })
+
+ const notMatched = await buildHogFunctionInvocations(
+ hogInputsService,
+ [fn],
+ createHogExecutionGlobals({ groups: {} })
+ )
+ expect(notMatched.invocations).toHaveLength(0)
+ expect(notMatched.metrics.map((m) => m.metric_name)).toEqual(['filtered'])
+
+ const matched = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())
+ expect(matched.invocations).toHaveLength(1)
+ expect(matched.metrics).toHaveLength(0)
+ })
+
+ // Filters that read elements_chain_* only match if the chain is parsed into the filter globals.
+ // The parsing itself is covered in hog-function-filtering.test.ts; these rows check that a real
+ // autocapture filter of each shape actually gates invocation building.
+ const elementsChainCases = [
+ {
+ shape: 'text',
+ filters: HOG_FILTERS_EXAMPLES.elements_text_filter,
+ notMatching: 'Not our text',
+ matching: 'Reload',
+ chain: (buttonText: string) =>
+ `span.LemonButton__content:attr__class="LemonButton__content"nth-child="2"nth-of-type="2"text="${buttonText}";span.LemonButton__chrome:attr__class="LemonButton__chrome"nth-child="1"nth-of-type="1";button.LemonButton.LemonButton--has-icon.LemonButton--secondary.LemonButton--status-default:attr__class="LemonButton LemonButton--secondary LemonButton--status-default LemonButton--has-icon"attr__type="button"nth-child="1"nth-of-type="1"text="${buttonText}";div.flex.gap-4.items-center:attr__class="flex gap-4 items-center"nth-child="1"nth-of-type="1"`,
+ },
+ {
+ shape: 'href',
+ filters: HOG_FILTERS_EXAMPLES.elements_href_filter,
+ notMatching: '/project/1/not-a-link',
+ matching: '/project/1/activity/explore',
+ chain: (link: string) =>
+ `span.LemonButton__content:attr__class="LemonButton__content"attr__href="${link}"href="${link}"nth-child="2"nth-of-type="2"text="Activity";a.LemonButton.Link.NavbarButton:attr__class="Link LemonButton NavbarButton"attr__href="${link}"href="${link}"nth-child="1"nth-of-type="1"text="Activity"`,
+ },
+ {
+ shape: 'tag and id',
+ filters: HOG_FILTERS_EXAMPLES.elements_tag_and_id_filter,
+ notMatching: 'notfound',
+ matching: 'homelink',
+ chain: (id: string) =>
+ `a.Link.font-semibold:attr__class="Link font-semibold"attr__href="/project/1/dashboard/1"attr__id="${id}"attr_id="${id}"href="/project/1/dashboard/1"nth-child="1"nth-of-type="1"text="My App Dashboard"`,
+ },
+ ]
+
+ it.each(elementsChainCases)(
+ 'gates invocation building on an elements-chain $shape filter',
+ async ({ filters, chain, notMatching, matching }) => {
+ const fn = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...filters,
+ })
+
+ const autocaptureGlobals = (elementsChain: string) =>
+ createHogExecutionGlobals({
+ groups: {},
+ event: {
+ uuid: 'uuid',
+ event: '$autocapture',
+ elements_chain: elementsChain,
+ distinct_id: 'distinct_id',
+ url: 'http://localhost:8000/events/1',
+ properties: { $lib_version: '1.2.3' },
+ timestamp: '2025-01-01T00:00:00.000Z',
+ },
+ })
+
+ const notMatched = await buildHogFunctionInvocations(
+ hogInputsService,
+ [fn],
+ autocaptureGlobals(chain(notMatching))
+ )
+ expect(notMatched.invocations).toHaveLength(0)
+ expect(notMatched.metrics.map((m) => m.metric_name)).toEqual(['filtered'])
+
+ const matched = await buildHogFunctionInvocations(
+ hogInputsService,
+ [fn],
+ autocaptureGlobals(chain(matching))
+ )
+ expect(matched.invocations).toHaveLength(1)
+ expect(matched.metrics).toHaveLength(0)
+ }
+ )
+
+ describe('mappings', () => {
+ const mappingFunction = () =>
+ createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ mappings: [
+ {
+ // Filters for pageview or autocapture, and overrides the url input
+ ...HOG_FILTERS_EXAMPLES.pageview_or_autocapture_filter,
+ inputs: {
+ url: {
+ order: 0,
+ value: 'https://example.com?q={event.event}',
+ bytecode: [
+ '_H',
+ 1,
+ 32,
+ 'https://example.com?q=',
+ 32,
+ 'event',
+ 32,
+ 'event',
+ 1,
+ 2,
+ 2,
+ 'concat',
+ 2,
+ ],
+ },
+ },
+ },
+ // No filters so should match all events
+ { ...HOG_FILTERS_EXAMPLES.no_filters },
+ // Broken filters so shouldn't match
+ { ...HOG_FILTERS_EXAMPLES.broken_filters },
+ ],
+ })
+
+ it('builds one invocation per matching mapping', async () => {
+ const results = await buildHogFunctionInvocations(
+ hogInputsService,
+ [mappingFunction()],
+ pageviewGlobals()
+ )
+
+ expect(results.invocations).toHaveLength(2)
+ expect(results.metrics.map((m) => m.metric_name)).toEqual(['filtering_failed'])
+ expect(results.logs.map((l) => l.message)).toMatchInlineSnapshot(`
+ [
+ "Error filtering event uuid: Invalid HogQL bytecode, stack is empty, can not pop",
+ ]
+ `)
+ })
+
+ it('skips mappings whose filters do not match', async () => {
+ const results = await buildHogFunctionInvocations(
+ hogInputsService,
+ [mappingFunction()],
+ createHogExecutionGlobals({ event: { event: 'test' } as any })
+ )
+
+ // Only the unfiltered mapping survives
+ expect(results.invocations).toHaveLength(1)
+ expect(results.metrics.map((m) => m.metric_name)).toEqual(['filtered', 'filtering_failed'])
+ })
+
+ it('resolves each matching mapping against its own inputs', async () => {
+ const { invocations } = await buildHogFunctionInvocations(
+ hogInputsService,
+ [mappingFunction()],
+ pageviewGlobals()
+ )
+
+ // The first mapping overrides url; both inherit the top-level headers
+ expect(invocations[0].state.globals.inputs.url).toBe('https://example.com?q=$pageview')
+ expect(invocations[0].state.globals.inputs.headers).toEqual({ version: 'v=' })
+ expect(invocations[1].state.globals.inputs.url).toBe('https://example.com/posthog-webhook')
+ expect(invocations[1].state.globals.inputs.headers).toEqual({ version: 'v=' })
+ })
+
+ // `mappings: []` takes the mapping path and matches nothing, so the function never runs.
+ // A destination saved with no mappings is silently a no-op rather than an unmapped send.
+ it('builds nothing for a function with an empty mappings array', async () => {
+ const fn = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ mappings: [],
+ })
+
+ const results = await buildHogFunctionInvocations(hogInputsService, [fn], pageviewGlobals())
+
+ expect(results.invocations).toHaveLength(0)
+ expect(results.metrics).toHaveLength(0)
+ })
+ })
+
+ it('reports a function whose inputs fail to build without dropping the rest of the batch', async () => {
+ const broken = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],
+ // Truncated bytecode - resolving this input throws
+ inputs: { url: { order: 0, value: 'https://example.com', bytecode: ['_H', 1, 2] } },
+ })
+ const healthy = createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+
+ const results = await buildHogFunctionInvocations(hogInputsService, [broken, healthy], pageviewGlobals())
+
+ expect(results.invocations.map((i) => i.functionId)).toEqual([healthy.id])
+ expect(results.metrics).toMatchObject([
+ { app_source_id: broken.id, metric_kind: 'failure', metric_name: 'inputs_failed', count: 1 },
+ ])
+ expect(results.logs).toMatchObject([
+ {
+ level: 'error',
+ log_source: 'hog_function',
+ log_source_id: broken.id,
+ message: expect.stringContaining('Error building inputs for event uuid:'),
+ },
+ ])
+ })
+ })
+
describe('cloneInvocation', () => {
beforeEach(() => {
const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.ts
index a372d0772789..072793815cb3 100644
--- a/nodejs/src/cdp/utils/invocation-utils.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.ts
@@ -1,13 +1,21 @@
// NOTE: PostIngestionEvent is our context event - it should never be sent directly to an output, but rather transformed into a lightweight schema
+import { DateTime } from 'luxon'
+
import { UUIDT } from '~/common/utils/utils'
+import type { HogInputsService } from '../services/hog-inputs.service'
import {
CyclotronJobInvocation,
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
+ HogFunctionFilterGlobals,
+ HogFunctionInvocationGlobals,
HogFunctionInvocationGlobalsWithInputs,
+ LogEntry,
+ MinimalAppMetric,
} from '../types'
import { HogFunctionType } from '../types'
+import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from './hog-function-filtering'
export function createInvocation(
globals: HogFunctionInvocationGlobalsWithInputs,
@@ -28,6 +36,129 @@ export function createInvocation(
}
}
+/**
+ * Matches a batch of hog functions against one event's globals and builds an invocation per match,
+ * resolving each one's inputs. Filter metrics/logs come back alongside for the caller to queue.
+ */
+export async function buildHogFunctionInvocations(
+ hogInputsService: HogInputsService,
+ hogFunctions: HogFunctionType[],
+ triggerGlobals: HogFunctionInvocationGlobals
+): Promise<{
+ invocations: CyclotronJobInvocationHogFunction[]
+ metrics: MinimalAppMetric[]
+ logs: LogEntry[]
+}> {
+ const metrics: MinimalAppMetric[] = []
+ const logs: LogEntry[] = []
+ const invocations: CyclotronJobInvocationHogFunction[] = []
+
+ // TRICKY: The frontend generates filters matching the Clickhouse event type so we are converting back
+ const filterGlobals = convertToHogFunctionFilterGlobal(triggerGlobals)
+
+ const _filterHogFunction = async (
+ hogFunction: HogFunctionType,
+ filters: HogFunctionType['filters'],
+ filterGlobals: HogFunctionFilterGlobals
+ ): Promise<boolean> => {
+ const filterResults = await filterFunctionInstrumented({
+ fn: hogFunction,
+ filters,
+ filterGlobals,
+ })
+
+ // Add any generated metrics and logs to our collections
+ metrics.push(...filterResults.metrics)
+ logs.push(...filterResults.logs)
+
+ return filterResults.match
+ }
+
+ const _buildInvocation = async (
+ hogFunction: HogFunctionType,
+ additionalInputs?: HogFunctionType['inputs']
+ ): Promise<CyclotronJobInvocationHogFunction | null> => {
+ try {
+ const globalsWithSource = {
+ ...triggerGlobals,
+ source: {
+ name: hogFunction.name ?? `Hog function: ${hogFunction.id}`,
+ url: `${triggerGlobals.project.url}/functions/${hogFunction.id}/configuration/`,
+ },
+ }
+
+ const globalsWithInputs = await hogInputsService.buildInputsWithGlobals(
+ hogFunction,
+ globalsWithSource,
+ additionalInputs
+ )
+
+ return createInvocation(globalsWithInputs, hogFunction)
+ } catch (error) {
+ logs.push({
+ team_id: hogFunction.team_id,
+ log_source: 'hog_function',
+ log_source_id: hogFunction.id,
+ instance_id: new UUIDT().toString(), // random UUID, like it would be for an invocation
+ timestamp: DateTime.now(),
+ level: 'error',
+ message: `Error building inputs for event ${triggerGlobals.event.uuid}: ${error.message}`,
+ })
+
+ metrics.push({
+ team_id: hogFunction.team_id,
+ app_source_id: hogFunction.id,
+ metric_kind: 'failure',
+ metric_name: 'inputs_failed',
+ count: 1,
+ })
+
+ return null
+ }
+ }
+
+ await Promise.all(
+ hogFunctions.map(async (hogFunction) => {
+ // We always check the top level filters
+ if (!(await _filterHogFunction(hogFunction, hogFunction.filters, filterGlobals))) {
+ return
+ }
+
+ // Check for non-mapping functions first
+ if (!hogFunction.mappings) {
+ const invocation = await _buildInvocation(hogFunction)
+ if (!invocation) {
+ return
+ }
+
+ invocations.push(invocation)
+ return
+ }
+
+ await Promise.all(
+ hogFunction.mappings.map(async (mapping) => {
+ if (!(await _filterHogFunction(hogFunction, mapping.filters, filterGlobals))) {
+ return
+ }
+
+ const invocation = await _buildInvocation(hogFunction, mapping.inputs ?? {})
+ if (!invocation) {
+ return
+ }
+
+ invocations.push(invocation)
+ })
+ )
+ })
+ )
+
+ return {
+ invocations,
+ metrics,
+ logs,
+ }
+}
+
/**
* Clones an invocation, removing all queue related values
*/
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 24edc936b9e1..94d52a9ea8b8 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -186,12 +186,14 @@ export type CommonConfig = BaseServerConfig & {
OTEL_SERVICE_ENVIRONMENT: string | null
// Shared between ingestion and CDP (used by hog transformer in both)
- CDP_HOG_WATCHER_SAMPLE_RATE: number
// Execute transformations on the Rust HogVM instead of the Node VM. Invocations the Rust VM
// can't run (unsupported host functions, addon not built) fall back to the Node VM.
CDP_HOG_RUST_VM_EXECUTION_ENABLED: boolean
+ /** Per-function wall-clock budget for an event transformation, enforced by the HogVM. */
+ TRANSFORMATIONS_HOG_TIMEOUT_MS: number
+
// Event loop yield helper (yieldEventLoopIfNeeded)
EVENT_LOOP_YIELD_THRESHOLD_MS: number
}
@@ -361,8 +363,8 @@ export function getDefaultCommonConfig(): CommonConfig {
OTEL_SERVICE_ENVIRONMENT: null,
// Shared between ingestion and CDP
- CDP_HOG_WATCHER_SAMPLE_RATE: 0,
CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
+ TRANSFORMATIONS_HOG_TIMEOUT_MS: 300,
// Event loop yield helper
EVENT_LOOP_YIELD_THRESHOLD_MS: 200,
diff --git a/nodejs/src/common/hog-transformations/hog-transformer.interface.ts b/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
index 32ca334ab85b..8df986ac9855 100644
--- a/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
+++ b/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
@@ -23,5 +23,4 @@ export interface HogTransformer {
transformEventAndProduceMessages(event: PluginEvent): Promise<HogTransformationResult>
// Refresh cached transformation hog-function states for the given teams (used by the ingestion
// prefetch step). Encapsulates the hog-function-manager lookup ingestion would otherwise reach into.
- prefetchTransformationStatesForTeams(teamIds: number[]): Promise<void>
}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.test.ts
deleted file mode 100644
index eee45486b01d..000000000000
--- a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.test.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { v4 } from 'uuid'
-
-import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
-import { PipelineResultType } from '~/ingestion/framework/results'
-import { ProjectId, Team } from '~/types'
-
-import { PrefetchHogFunctionsStepInput, createPrefetchHogFunctionsStep } from './prefetch-hog-functions-step'
-
-const createTestTeam = (overrides: Partial<Team> = {}): Team => ({
- id: 1,
- project_id: 1 as ProjectId,
- organization_id: 'test-org-id',
- uuid: v4(),
- name: 'Test Team',
- anonymize_ips: false,
- api_token: 'test-api-token',
- secret_api_token: null,
- session_recording_opt_in: true,
- person_processing_opt_out: null,
- heatmaps_opt_in: null,
- ingested_event: true,
- person_display_name_properties: null,
- minimal_flag_called_events: false,
- test_account_filters: null,
- cookieless_server_hash_mode: null,
- timezone: 'UTC',
- available_features: [],
- drop_events_older_than_seconds: null,
- extra_settings: null,
- ...overrides,
-})
-
-const createTestInput = (team: Team): PrefetchHogFunctionsStepInput => ({
- team,
-})
-
-describe('prefetchHogFunctionsStep', () => {
- // The step only depends on the HogTransformer contract; it delegates the actual clear/fetch/cache
- // work to prefetchTransformationStatesForTeams (covered by the hog-transformer service tests).
- let prefetchTransformationStatesForTeams: jest.Mock
- let mockHogTransformer: HogTransformer
-
- beforeEach(() => {
- prefetchTransformationStatesForTeams = jest.fn().mockResolvedValue(undefined)
- mockHogTransformer = { prefetchTransformationStatesForTeams } as unknown as HogTransformer
- })
-
- it('refreshes transformation states for the batch team IDs', async () => {
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 1)
-
- await step([createTestInput(createTestTeam({ id: 1 }))])
-
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledWith([1])
- })
-
- it('returns an empty array and still refreshes with no team IDs when no events provided', async () => {
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 1)
-
- const results = await step([])
-
- expect(results).toEqual([])
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledWith([])
- })
-
- it('deduplicates team IDs across the batch', async () => {
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 1)
- const team1 = createTestTeam({ id: 1 })
- const team2 = createTestTeam({ id: 2 })
- const team3 = createTestTeam({ id: 3 })
-
- await step([
- createTestInput(team1),
- createTestInput(team1),
- createTestInput(team2),
- createTestInput(team3),
- createTestInput(team2),
- ])
-
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledTimes(1)
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledWith([1, 2, 3])
- })
-
- it('returns all events as OK results unchanged', async () => {
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 1)
- const team = createTestTeam({ id: 1 })
- const inputs = [
- { team, extraField: 'value1' },
- { team, extraField: 'value2' },
- ]
-
- const results = await step(inputs)
-
- expect(results).toHaveLength(2)
- expect(results[0].type).toBe(PipelineResultType.OK)
- expect(results[1].type).toBe(PipelineResultType.OK)
- if (results[0].type === PipelineResultType.OK && results[1].type === PipelineResultType.OK) {
- expect(results[0].value).toEqual(inputs[0])
- expect(results[1].value).toEqual(inputs[1])
- }
- })
-
- describe('sampling rate', () => {
- let mockRandom: jest.SpyInstance
-
- beforeEach(() => {
- mockRandom = jest.spyOn(Math, 'random')
- })
-
- afterEach(() => {
- mockRandom.mockRestore()
- })
-
- it('prefetches when random value is below sample rate', async () => {
- mockRandom.mockReturnValue(0.2)
-
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 0.3)
-
- await step([createTestInput(createTestTeam({ id: 1 }))])
-
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledWith([1])
- })
-
- it('skips prefetching when random value is above sample rate', async () => {
- mockRandom.mockReturnValue(0.4)
-
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 0.3)
-
- const results = await step([createTestInput(createTestTeam({ id: 1 }))])
-
- expect(prefetchTransformationStatesForTeams).not.toHaveBeenCalled()
- expect(results).toHaveLength(1)
- })
-
- it('skips prefetching when random value equals sample rate', async () => {
- mockRandom.mockReturnValue(0.3)
-
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 0.3)
-
- await step([createTestInput(createTestTeam({ id: 1 }))])
-
- // 0.3 < 0.3 is false, so should skip
- expect(prefetchTransformationStatesForTeams).not.toHaveBeenCalled()
- })
-
- it('always prefetches when sample rate is 1', async () => {
- mockRandom.mockReturnValue(0.999)
-
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 1)
-
- await step([createTestInput(createTestTeam({ id: 1 }))])
-
- expect(prefetchTransformationStatesForTeams).toHaveBeenCalledWith([1])
- })
-
- it('skips prefetching when sample rate is 0', async () => {
- mockRandom.mockReturnValue(0.5)
-
- const step = createPrefetchHogFunctionsStep(mockHogTransformer, 0)
-
- await step([createTestInput(createTestTeam({ id: 1 }))])
-
- expect(prefetchTransformationStatesForTeams).not.toHaveBeenCalled()
- })
- })
-})
diff --git a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts b/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts
deleted file mode 100644
index be444e08abf4..000000000000
--- a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
-import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
-import { PipelineResult, ok } from '~/ingestion/framework/results'
-import { Team } from '~/types'
-
-export interface PrefetchHogFunctionsStepInput {
- team: Team
-}
-
-export function createPrefetchHogFunctionsStep<TInput extends PrefetchHogFunctionsStepInput>(
- hogTransformer: HogTransformer,
- sampleRate: number
-): ChunkProcessingStep<TInput, TInput> {
- return async function prefetchHogFunctionsStep(events: TInput[]): Promise<PipelineResult<TInput>[]> {
- // Skip prefetching if sampling determines we shouldn't run hog watcher
- const shouldRunHogWatcher = Math.random() < sampleRate
- if (!shouldRunHogWatcher) {
- return events.map((event) => ok(event))
- }
-
- // Extract unique team IDs from the batch
- const teamIds = new Set<number>()
- for (const event of events) {
- teamIds.add(event.team.id)
- }
-
- // Refresh cached transformation states for the teams in this batch
- await hogTransformer.prefetchTransformationStatesForTeams(Array.from(teamIds))
-
- // Return events unchanged
- return events.map((event) => ok(event))
- }
-}
diff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.ts
index e6b17da8091e..403efa6c6410 100644
--- a/nodejs/src/ingestion/ingestion-consumer.test.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts
@@ -6,7 +6,7 @@ import { DateTime } from 'luxon'
import { Message } from 'node-rdkafka'
import { insertHogFunction as _insertHogFunction } from '~/cdp/_tests/fixtures'
-import { HogTransformerService, createHogTransformerService } from '~/cdp/hog-transformations/hog-transformer.service'
+import { createHogTransformerService } from '~/cdp/hog-transformations/hog-transformer.service'
import { template as geoipTemplate } from '~/cdp/templates/_transformations/geoip/geoip.template'
import { compileHog } from '~/cdp/templates/compiler'
import { HogFunctionType } from '~/cdp/types'
@@ -1313,82 +1313,6 @@ describe('IngestionConsumer', () => {
ingester = await createIngestionConsumer(infra)
})
- it(
- 'should call hogwatcher state caching methods and observe results when hogwatcher is enabled (sample rate = 1)',
- async () => {
- // Create a new ingester with the sample rate we want to test
- infra.config.CDP_HOG_WATCHER_SAMPLE_RATE = 1
- const localIngester = await createIngestionConsumer(infra)
-
- // Create spies for methods after the service is configured. The consumer exposes the
- // transformer via its interface, so cast to the concrete service for these internal spies.
- const concreteTransformer = localIngester.hogTransformer as HogTransformerService
- const fetchAndCacheSpy = jest.spyOn(concreteTransformer, 'fetchAndCacheHogFunctionStates')
- const clearStatesSpy = jest.spyOn(concreteTransformer, 'clearHogFunctionStates')
- const observeResultsSpy = jest.spyOn(concreteTransformer['hogWatcher'], 'observeResults')
-
- // Process batch with hogwatcher enabled
- // in this stage we do not have the teamId on the event but the token is in kafka headers
- const event = createEvent({
- ip: '89.160.20.129',
- properties: { $ip: '89.160.20.129' },
- })
- const messages = createKafkaMessages([event])
-
- await localIngester.handleKafkaBatch(messages)
-
- // Verify that fetchAndCacheHogFunctionStates and clearHogFunctionStates were called
- expect(fetchAndCacheSpy).toHaveBeenCalled()
- expect(clearStatesSpy).toHaveBeenCalled()
-
- // Verify the full integration flow worked
- expect(observeResultsSpy).toHaveBeenCalled()
-
- // Verify that results were passed to observeResults with the correct structure
- const results = observeResultsSpy.mock.calls[0][0]
- expect(results).toBeInstanceOf(Array)
- expect(results.length).toBeGreaterThan(0)
-
- // Check that the results contain our transformation function
- const functionResult = results.find((r) => r.invocation.functionId === transformationFunction.id)
- expect(functionResult).toBeDefined()
- expect(functionResult?.finished).toBe(true)
-
- await localIngester.stop()
- },
- TRANSFORMATION_TEST_TIMEOUT
- )
-
- it(
- 'should not call hogwatcher state caching methods when hogwatcher is disabled (sample rate = 0)',
- async () => {
- // Create a new ingester with the sample rate we want to test
- infra.config.CDP_HOG_WATCHER_SAMPLE_RATE = 0
- const localIngester = await createIngestionConsumer(infra)
-
- // Create spies for methods after the service is configured (cast to the concrete service)
- const concreteTransformer = localIngester.hogTransformer as HogTransformerService
- const fetchAndCacheSpy = jest.spyOn(concreteTransformer, 'fetchAndCacheHogFunctionStates')
- const clearStatesSpy = jest.spyOn(concreteTransformer, 'clearHogFunctionStates')
-
- // Process batch with hogwatcher disabled
- const event = createEvent({
- ip: '89.160.20.129',
- properties: { $ip: '89.160.20.129' },
- })
- const messages = createKafkaMessages([event])
-
- await localIngester.handleKafkaBatch(messages)
-
- // Verify that fetchAndCacheHogFunctionStates and clearHogFunctionStates were NOT called
- expect(fetchAndCacheSpy).not.toHaveBeenCalled()
- expect(clearStatesSpy).not.toHaveBeenCalled()
-
- await localIngester.stop()
- },
- TRANSFORMATION_TEST_TIMEOUT
- )
-
it(
'should invoke transformation for matching team with error case',
async () => {
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index f501e8595ab7..da0dfeb44cfc 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -65,7 +65,7 @@ import { AiEventSubpipelineFactory } from './common/subpipelines/ai-subpipeline.
import { IngestionConsumerConfig, IngestionOutputsConfig } from './config'
export type IngestionConsumerFullConfig = IngestionConsumerConfig &
- Pick<CommonConfig, 'KAFKA_CLIENT_RACK' | 'CDP_HOG_WATCHER_SAMPLE_RATE'> &
+ Pick<CommonConfig, 'KAFKA_CLIENT_RACK'> &
// The general server builds the consumer from a config that includes IngestionOutputsConfig; the
// merge-events gate reads the topic, so surface it here rather than relying on the runtime shape.
Pick<IngestionOutputsConfig, 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC'>
@@ -279,7 +279,6 @@ export class IngestionConsumer {
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
- cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs,
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts
index bab58507acb1..6db274fd6ebc 100644
--- a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts
@@ -30,7 +30,6 @@ describe('createAiConsumer', () => {
SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID: '',
INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',
EVENT_SCHEMA_ENFORCEMENT_ENABLED: false,
- CDP_HOG_WATCHER_SAMPLE_RATE: 1,
// Read eagerly by createAiConsumer (not deferred like the scope-builder services
// below), so these need real fail-closed values rather than the cast-away pattern.
AI_BLOB_S3_BUCKET: '',
diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.ts
index 41c06164bbab..c3910d22be54 100644
--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts
@@ -1,4 +1,3 @@
-import { CommonConfig } from '~/common/config'
import { buildIntegerMatcher } from '~/common/config/config'
import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
@@ -67,8 +66,7 @@ export type AiConsumerConfig = CommonIngestionConsumerConfig &
| 'AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT'
| 'AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY'
| 'AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS'
- > &
- Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE'>
+ >
/** Outputs the AI pipeline emits to. The same instance backs the hog transformer's
* monitoring (app_metrics + log_entries), wired up server-side. */
@@ -195,7 +193,6 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiShared
overflowRedirectService: container.overflowRedirectService,
overflowLaneTTLRefreshService: container.overflowLaneTTLRefreshService,
concurrentBatches: config.INGESTION_WORKER_CONCURRENT_BATCHES,
- cdpHogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,
eventSchemaEnforcementEnabled: config.EVENT_SCHEMA_ENFORCEMENT_ENABLED,
eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres),
topHog: container.topHog,
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
index ce9352d2113a..3e0aa37e5b6f 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
@@ -38,10 +38,7 @@ describe('AiIngestionPipeline', () => {
let mockEventFilterManager: { getFilter: jest.Mock }
let mockCookielessManager: jest.Mocked<CookielessManager>
let mockHogTransformer: jest.Mocked<
- Pick<
- HogTransformer,
- 'transformEventAndProduceMessages' | 'processInvocationResults' | 'prefetchTransformationStatesForTeams'
- >
+ Pick<HogTransformer, 'transformEventAndProduceMessages' | 'processInvocationResults'>
>
let mockPersonRepository: jest.Mocked<PersonReadRepository>
let mockGroupTypeManager: jest.Mocked<ReadOnlyGroupTypeManager>
@@ -124,12 +121,8 @@ describe('AiIngestionPipeline', () => {
.fn()
.mockImplementation((event) => Promise.resolve({ event, invocationResults: [] })),
processInvocationResults: jest.fn().mockResolvedValue(undefined),
- prefetchTransformationStatesForTeams: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<
- Pick<
- HogTransformer,
- 'transformEventAndProduceMessages' | 'processInvocationResults' | 'prefetchTransformationStatesForTeams'
- >
+ Pick<HogTransformer, 'transformEventAndProduceMessages' | 'processInvocationResults'>
>
mockPersonRepository = {
@@ -171,7 +164,6 @@ describe('AiIngestionPipeline', () => {
overflowRedirectService: new DisabledOverflowRedirect(),
overflowLaneTTLRefreshService: new DisabledOverflowRedirect(),
concurrentBatches: 1,
- cdpHogWatcherSampleRate: 1,
eventSchemaEnforcementEnabled: false,
eventSchemaEnforcementManager: {} as unknown as EventSchemaEnforcementManager,
topHog: createNoopTopHog(),
@@ -225,6 +217,5 @@ describe('AiIngestionPipeline', () => {
// Without this prefetch the transformer can't see Hog watcher's disabled state,
// so disabled transformations would still run.
- expect(mockHogTransformer.prefetchTransformationStatesForTeams).toHaveBeenCalledWith([123])
})
})
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
index 464f82c497d0..00a7a0f38073 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -40,7 +40,6 @@ import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-pr
import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'
import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'
import { createNormalizeProcessPersonFlagStep } from '~/ingestion/common/steps/event-processing/normalize-process-person-flag-step'
-import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-processing/prefetch-hog-functions-step'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'
import { createSplitAiEventsStep } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
@@ -80,7 +79,6 @@ export interface AiIngestionPipelineConfig {
overflowRedirectService: OverflowRedirectService
overflowLaneTTLRefreshService: OverflowRedirectService
concurrentBatches: number
- cdpHogWatcherSampleRate: number
eventSchemaEnforcementEnabled: boolean
eventSchemaEnforcementManager: EventSchemaEnforcementManager
topHog: TopHogRegistry
@@ -129,7 +127,6 @@ export function createAiIngestionPipeline<
overflowRedirectService,
overflowLaneTTLRefreshService,
concurrentBatches,
- cdpHogWatcherSampleRate,
eventSchemaEnforcementEnabled,
eventSchemaEnforcementManager,
topHog,
@@ -183,9 +180,6 @@ export function createAiIngestionPipeline<
.pipeChunk(createFetchPersonChunkStep(personRepository), {
retry: { tries: 5, sleepMs: 100, name: 'fetch_person_chunk' },
})
- // Prefetch hog functions for the batch's teams so the transformer
- // honors Hog watcher's disabled-function state (mirrors analytics).
- .pipeChunk(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))
// Per-event chain. Retry is applied per step: only the steps
// that do transient-failure-prone I/O (hog transform, group-type
// fetch, emit) retry, matching the analytics per-distinct-id path.
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 0dddcb76e0e4..aeebc2d4ee20 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -61,7 +61,6 @@ export interface JoinedIngestionPipelineConfig {
preservePartitionLocality: boolean
personsPrefetchEnabled: boolean
groupsPrefetchEnabled: boolean
- cdpHogWatcherSampleRate: number
outputs: IngestionOutputs<
| EventOutput
| AiEventOutput
@@ -128,7 +127,6 @@ export function createJoinedIngestionPipeline<
preservePartitionLocality,
personsPrefetchEnabled,
groupsPrefetchEnabled,
- cdpHogWatcherSampleRate,
outputs,
perDistinctIdOptions,
concurrentBatches,
@@ -169,8 +167,6 @@ export function createJoinedIngestionPipeline<
groupTypeManager,
flagCalledPersonlessDefaultTeams: perDistinctIdOptions.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
personlessWritesDisabledTeams: perDistinctIdOptions.PERSONLESS_WRITES_DISABLED_TEAMS,
- hogTransformer,
- cdpHogWatcherSampleRate,
}
const perEventConfig: PerDistinctIdPipelineConfig = {
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index 6227a0091e00..fcb747cc26c8 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -1,7 +1,6 @@
import { Message } from 'node-rdkafka'
import { GroupTypeManager } from '~/common/groups/group-type-manager'
-import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
@@ -23,7 +22,6 @@ import {
createValidateEventSchemaStep,
} from '~/ingestion/common/steps/event-preprocessing'
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
-import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-processing/prefetch-hog-functions-step'
import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
import { prefetchGroupsStep } from '~/ingestion/pipelines/analytics/steps/prefetchGroupsStep'
import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'
@@ -56,8 +54,6 @@ export interface PostTeamPreprocessingSubpipelineConfig {
groupTypeManager: GroupTypeManager
flagCalledPersonlessDefaultTeams: string
personlessWritesDisabledTeams: string
- hogTransformer: HogTransformer
- cdpHogWatcherSampleRate: number
}
export function createPostTeamPreprocessingSubpipeline<
@@ -85,8 +81,6 @@ export function createPostTeamPreprocessingSubpipeline<
groupTypeManager,
flagCalledPersonlessDefaultTeams,
personlessWritesDisabledTeams,
- hogTransformer,
- cdpHogWatcherSampleRate,
} = config
return (
@@ -143,7 +137,5 @@ export function createPostTeamPreprocessingSubpipeline<
},
}
)
- // Prefetch hog functions for all teams in the batch
- .pipeChunk(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))
)
}
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index 14ced98593f5..7f70e2d33068 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -80,9 +80,6 @@ export type LogsIngestionConsumerConfig = {
LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS: number
/** Max failed invocations whose logs are captured, per function per message. */
LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION: number
- /** Fraction of messages (0–1) on which HogWatcher state is read and aggregate VM cost reported.
- * 0 (default) keeps the watcher fully dormant — no Redis traffic. */
- LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE: number
REDIS_URL: string
REDIS_POOL_MIN_SIZE: number
REDIS_POOL_MAX_SIZE: number
@@ -121,7 +118,6 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo
LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS: 100,
LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS: 2000,
LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION: 3,
- LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE: 0,
// Overlapping fields with CommonConfig, included for standalone usage
// ok to connect to localhost over plaintext
// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
index ed33618b6704..eeb1f325df9c 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -2190,7 +2190,6 @@ describe('LogsIngestionConsumer', () => {
messageBudgetMs: 100,
batchBudgetMs: 2000,
maxErrorLogsPerFunctionPerMessage: 3,
- hogWatcherSampleRate: 0,
})
}
diff --git a/nodejs/src/logs/transformations/logs-transformer.service.test.ts b/nodejs/src/logs/transformations/logs-transformer.service.test.ts
index 71f0c681e79b..2b5588fc3224 100644
--- a/nodejs/src/logs/transformations/logs-transformer.service.test.ts
+++ b/nodejs/src/logs/transformations/logs-transformer.service.test.ts
@@ -1,6 +1,5 @@
import { HogFunctionManagerService } from '~/cdp/services/managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from '~/cdp/services/monitoring/hog-function-monitoring.service'
-import { HogWatcherService, HogWatcherState } from '~/cdp/services/monitoring/hog-watcher.service'
import { compileHog } from '~/cdp/templates/compiler'
import { HogFunctionType } from '~/cdp/types'
@@ -85,7 +84,6 @@ describe('LogsTransformerService', () => {
messageBudgetMs: 50,
batchBudgetMs: 2000,
maxErrorLogsPerFunctionPerMessage: 3,
- hogWatcherSampleRate: 0,
}
service = new LogsTransformerService(manager as any, monitoring as any, config)
})
@@ -496,87 +494,6 @@ describe('LogsTransformerService', () => {
expect(monitoring.flush).toHaveBeenCalled()
})
- describe('HogWatcher integration', () => {
- const createMockWatcher = (): jest.Mocked<
- Pick<HogWatcherService, 'getEffectiveStates' | 'observeAggregatedResults'>
- > =>
- ({
- getEffectiveStates: jest.fn().mockResolvedValue({}),
- observeAggregatedResults: jest.fn().mockResolvedValue(undefined),
- }) as any
-
- const withWatcher = (watcher: any, sampleRate: number): LogsTransformerService =>
- new LogsTransformerService(
- manager as any,
- monitoring as any,
- { ...config, hogWatcherSampleRate: sampleRate },
- watcher
- )
-
- it('never touches the watcher when the sample rate is 0', async () => {
- const watcher = createMockWatcher()
- service = withWatcher(watcher, 0)
- setFunctions([await createFunction('return record')])
-
- await service.transformRecords(TEAM_ID, [createRecord()])
-
- expect(watcher.getEffectiveStates).not.toHaveBeenCalled()
- expect(watcher.observeAggregatedResults).not.toHaveBeenCalled()
- })
-
- it('reports one aggregated observation per function when sampled', async () => {
- const watcher = createMockWatcher()
- service = withWatcher(watcher, 1)
- const fn = await createFunction('return record')
- setFunctions([fn])
-
- await service.transformRecords(TEAM_ID, [createRecord(), createRecord()])
-
- expect(watcher.observeAggregatedResults).toHaveBeenCalledTimes(1)
- const observations = watcher.observeAggregatedResults.mock.calls[0][0]
- expect(observations).toHaveLength(1)
- expect(observations[0].hogFunction.id).toEqual(fn.id)
- expect(observations[0].totalDurationMs).toBeGreaterThanOrEqual(0)
- })
-
- it('skips functions the watcher has disabled and records a metric', async () => {
- const watcher = createMockWatcher()
- const fn = await createFunction('return null') // would drop every record if it ran
- watcher.getEffectiveStates.mockResolvedValue({ [fn.id]: { state: HogWatcherState.disabled, tokens: 0 } })
- service = withWatcher(watcher, 1)
- setFunctions([fn])
-
- const records = [createRecord(), createRecord()]
- const { recordsDropped } = await service.transformRecords(TEAM_ID, records)
-
- expect(recordsDropped).toEqual(0)
- expect(records).toHaveLength(2)
- expect(watcher.observeAggregatedResults).not.toHaveBeenCalled()
- expect(queuedMetrics()).toContainEqual(
- expect.objectContaining({ metric_name: 'disabled_permanently', app_source_id: fn.id, count: 2 })
- )
- })
-
- it('runs all functions untouched by the watcher when the state read throws', async () => {
- const watcher = createMockWatcher()
- watcher.getEffectiveStates.mockRejectedValue(new Error('redis down'))
- service = withWatcher(watcher, 1)
- setFunctions([
- await createFunction(`
- let rec := record
- rec.body := 'transformed'
- return rec
- `),
- ])
-
- const records = [createRecord()]
- const { recordsDropped } = await service.transformRecords(TEAM_ID, records)
-
- expect(recordsDropped).toBe(0)
- expect(records[0].body).toBe('transformed')
- })
- })
-
describe('fail-open on infrastructure errors', () => {
it('passes records through untouched when the function fetch throws', async () => {
manager.getHogFunctionsForTeams.mockRejectedValue(new Error('pg down'))
diff --git a/nodejs/src/logs/transformations/logs-transformer.service.ts b/nodejs/src/logs/transformations/logs-transformer.service.ts
index 56e49c9941a1..e0bc1b5a3ec0 100644
--- a/nodejs/src/logs/transformations/logs-transformer.service.ts
+++ b/nodejs/src/logs/transformations/logs-transformer.service.ts
@@ -3,7 +3,6 @@ import { Counter, Histogram } from 'prom-client'
import { HogFunctionManagerService } from '~/cdp/services/managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from '~/cdp/services/monitoring/hog-function-monitoring.service'
-import { HogWatcherService, HogWatcherState } from '~/cdp/services/monitoring/hog-watcher.service'
import { HogFunctionType, LogEntry } from '~/cdp/types'
import { sanitizeLogMessage } from '~/cdp/utils'
import { yieldEventLoopIfNeeded } from '~/common/utils/event-loop-yield'
@@ -86,9 +85,6 @@ export interface LogsTransformerConfig {
batchBudgetMs: number
/** Max failed invocations whose print/error logs are captured, per function per message */
maxErrorLogsPerFunctionPerMessage: number
- /** Fraction of messages on which HogWatcher state is read and aggregate cost reported.
- * 0 disables the watcher entirely (no Redis reads, no observations). */
- hogWatcherSampleRate: number
}
/** Tracks cumulative VM time across all messages of one consumer batch. */
@@ -135,8 +131,7 @@ export class LogsTransformerService {
constructor(
private hogFunctionManager: HogFunctionManagerService,
private monitoring: HogFunctionMonitoringService,
- private config: LogsTransformerConfig,
- private hogWatcher?: HogWatcherService
+ private config: LogsTransformerConfig
) {}
public startBatch(): TransformationBatchBudget {
@@ -196,10 +191,7 @@ export class LogsTransformerService {
// On a sampled message the watcher reads state (to skip disabled functions) and, at the
// end, receives the aggregate cost. A sample rate of 0 means no Redis traffic at all.
- const runWatcher = !!this.hogWatcher && Math.random() < this.config.hogWatcherSampleRate
- const functions = runWatcher
- ? await this.dropWatcherDisabled(teamId, allFunctions, records.length)
- : allFunctions
+ const functions = allFunctions
if (functions.length === 0) {
return { recordsDropped, recordsDroppedByFunctionId }
}
@@ -279,79 +271,9 @@ export class LogsTransformerService {
transformationVmDurationHistogram.observe(messageVmMs / 1000)
this.queueAggregates(teamId, aggregates)
- if (runWatcher) {
- this.reportToWatcher(functions, aggregates)
- }
-
return { recordsDropped, recordsDroppedByFunctionId }
}
- /** Reads watcher state once per message and removes functions it has disabled. */
- private async dropWatcherDisabled(
- teamId: number,
- functions: HogFunctionType[],
- recordCount: number
- ): Promise<HogFunctionType[]> {
- if (!this.hogWatcher) {
- return functions
- }
- let states: Awaited<ReturnType<HogWatcherService['getEffectiveStates']>>
- try {
- states = await this.hogWatcher.getEffectiveStates(functions.map((fn) => fn.id))
- } catch (error) {
- // Fail open: a Redis blip on a sampled message must not DLQ it — run every
- // function as if unsampled rather than propagate.
- transformationInfraErrorsCounter.inc({ source: 'watcher_state' })
- logger.warn('[logs-transformer] watcher state read failed — running all functions', {
- teamId,
- error: String(error),
- })
- return functions
- }
- const active: HogFunctionType[] = []
- for (const fn of functions) {
- if (states[fn.id]?.state === HogWatcherState.disabled) {
- transformationRecordsCounter.inc({ result: 'watcher_disabled' }, recordCount)
- this.monitoring.queueAppMetric(
- {
- team_id: teamId,
- app_source_id: fn.id,
- metric_kind: 'failure',
- metric_name: 'disabled_permanently',
- count: recordCount,
- },
- 'hog_function'
- )
- } else {
- active.push(fn)
- }
- }
- return active
- }
-
- /** Reports one aggregated VM-time observation per function for this message. Fire-and-forget. */
- private reportToWatcher(functions: HogFunctionType[], aggregates: Map<string, FunctionAggregates>): void {
- if (!this.hogWatcher) {
- return
- }
- const byId = new Map(functions.map((fn) => [fn.id, fn]))
- const observations: { hogFunction: HogFunctionType; totalDurationMs: number }[] = []
- for (const [functionId, agg] of aggregates) {
- const hogFunction = byId.get(functionId)
- // A 0ms aggregate still costs nothing, but reporting it keeps token refill honest.
- if (hogFunction) {
- observations.push({ hogFunction, totalDurationMs: agg.totalDurationMs })
- }
- }
- if (observations.length > 0) {
- this.hogWatcher.observeAggregatedResults(observations).catch((error) => {
- logger.warn('⚠️', '[logs-transformer] HogWatcher observeAggregatedResults failed', {
- error: String(error),
- })
- })
- }
- }
-
/** Runs every function in execution order against one record. Returns true if dropped. */
private transformSingleRecord(
record: LogRecord,
diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.ts
index 64bd994c8c09..5b87ea72ef14 100644
--- a/nodejs/src/servers/error-tracking-server.ts
+++ b/nodejs/src/servers/error-tracking-server.ts
@@ -58,7 +58,9 @@ import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from
* This is the union of:
* - BaseServerConfig: HTTP server, profiling, pod termination lifecycle
* - ErrorTrackingConsumerConfig: error tracking pipeline, cymbal, overflow
- * - HogTransformerServiceConfig: CDP keys needed by the hog transformer running in-process
+ * - HogTransformerServiceConfig: the transformation-only keys the in-process hog transformer reads.
+ * No CDP delivery config (Redis, watcher, SES, fetch) - transformations run the synchronous
+ * Hog core alone, so those keys are deliberately absent rather than inherited.
* - Infrastructure configs: Kafka broker, Postgres, Redis, consumer tuning
* - Remaining CommonConfig picks: server mode, services, observability
*/
@@ -79,6 +81,7 @@ export type ErrorTrackingServerConfig = BaseServerConfig &
| 'LOG_LEVEL'
| 'PLUGIN_SERVER_MODE'
| 'CLOUD_DEPLOYMENT'
+ | 'ENCRYPTION_SALT_KEYS'
| 'MMDB_FILE_LOCATION'
| 'CAPTURE_INTERNAL_URL'
| 'HEALTHCHECK_MAX_STALE_SECONDS'
@@ -185,7 +188,6 @@ export class ErrorTrackingServer implements NodeServer {
encryptedFields,
integrationManager,
monitoringOutputs: outputs,
- teamManager,
}
// 3. Error tracking consumer
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 1e64e94a79c6..62c6ddda67be 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -106,6 +106,7 @@ export type IngestionApiServerConfig = BaseServerConfig &
| 'LOG_LEVEL'
| 'PLUGIN_SERVER_MODE'
| 'CLOUD_DEPLOYMENT'
+ | 'ENCRYPTION_SALT_KEYS'
| 'MMDB_FILE_LOCATION'
| 'CAPTURE_INTERNAL_URL'
| 'LAZY_LOADER_DEFAULT_BUFFER_MS'
@@ -308,7 +309,6 @@ export class IngestionApiServer implements NodeServer {
encryptedFields,
integrationManager,
monitoringOutputs: ingestionOutputs,
- teamManager,
}
this.hogTransformer = createHogTransformerService(this.config, hogTransformerDeps)
await this.hogTransformer.start()
@@ -385,7 +385,6 @@ export class IngestionApiServer implements NodeServer {
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
- cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs: ingestionOutputs,
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index 5c5cc165315f..e6d00e450e23 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -68,7 +68,9 @@ import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from
* This is the union of:
* - BaseServerConfig: HTTP server, profiling, pod termination lifecycle
* - IngestionConsumerConfig: ingestion pipeline, person/group processing, overflow, cookieless, etc.
- * - HogTransformerServiceConfig: CDP keys needed by the hog transformer running in-process
+ * - HogTransformerServiceConfig: the transformation-only keys the in-process hog transformer reads.
+ * No CDP delivery config (Redis, watcher, SES, fetch) - transformations run the synchronous
+ * Hog core alone, so those keys are deliberately absent rather than inherited.
* - Infrastructure configs: Kafka broker, Postgres, Redis, consumer tuning
* - Remaining CommonConfig picks: server mode, services, observability
*
@@ -90,6 +92,7 @@ export type IngestionGeneralServerConfig = BaseServerConfig &
| 'LOG_LEVEL'
| 'PLUGIN_SERVER_MODE'
| 'CLOUD_DEPLOYMENT'
+ | 'ENCRYPTION_SALT_KEYS'
| 'MMDB_FILE_LOCATION'
| 'CAPTURE_INTERNAL_URL'
| 'LAZY_LOADER_DEFAULT_BUFFER_MS'
@@ -263,7 +266,6 @@ export class IngestionGeneralServer implements NodeServer {
encryptedFields,
integrationManager,
monitoringOutputs: ingestionOutputs,
- teamManager,
}
const ingestionDeps: IngestionConsumerDeps = {
diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.ts
index d512b81f6ee5..1da804a65969 100644
--- a/nodejs/src/servers/ingestion-logs-server.ts
+++ b/nodejs/src/servers/ingestion-logs-server.ts
@@ -1,7 +1,6 @@
import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { createPosthogRedisConnectionConfig } from '~/common/config/redis-pools'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
-import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { QuotaLimiting } from '~/common/services/quota-limiting.service'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { createRedisPoolFromConfig } from '~/common/utils/db/redis'
@@ -28,10 +27,8 @@ import { createLogsOutputsRegistry } from '~/logs/outputs/registry'
import { SamplingRulesCache } from '~/logs/sampling/sampling-rules-cache'
import { LogsTransformerService } from '~/logs/transformations/logs-transformer.service'
-import type { CdpConfig } from '../cdp/config'
import { HogFunctionManagerService } from '../cdp/services/managers/hog-function-manager.service'
import { HogFunctionMonitoringService } from '../cdp/services/monitoring/hog-function-monitoring.service'
-import { HogWatcherService } from '../cdp/services/monitoring/hog-watcher.service'
import { EncryptedFields } from '../cdp/utils/encryption-utils'
import { CommonConfig } from '../common/config'
import { DatabaseConnectionConfig, KafkaBrokerConfig, RedisConnectionsConfig } from '../ingestion/config'
@@ -65,29 +62,6 @@ export type IngestionLogsServerConfig = BaseServerConfig &
| 'HEALTHCHECK_MAX_STALE_SECONDS'
| 'ENCRYPTION_SALT_KEYS'
| 'SITE_URL'
- > &
- // HogWatcher for log transformations shares CDP's redis + tuning so function
- // health state is read and written where the API and CDP consumers expect it.
- Pick<
- CdpConfig,
- | 'CDP_REDIS_HOST'
- | 'CDP_REDIS_PORT'
- | 'CDP_REDIS_PASSWORD'
- | 'CDP_WATCHER_HOG_COST_TIMING_LOWER_MS'
- | 'CDP_WATCHER_HOG_COST_TIMING_UPPER_MS'
- | 'CDP_WATCHER_HOG_COST_TIMING'
- | 'CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS'
- | 'CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS'
- | 'CDP_WATCHER_ASYNC_COST_TIMING'
- | 'CDP_WATCHER_SEND_EVENTS'
- | 'CDP_WATCHER_BUCKET_SIZE'
- | 'CDP_WATCHER_REFILL_RATE'
- | 'CDP_WATCHER_TTL'
- | 'CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS'
- | 'CDP_WATCHER_THRESHOLD_DEGRADED'
- | 'CDP_WATCHER_STATE_LOCK_TTL'
- | 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS'
- | 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS'
>
export class IngestionLogsServer implements NodeServer {
@@ -166,54 +140,13 @@ export class IngestionLogsServer implements NodeServer {
)
const hogFunctionMonitoring = new HogFunctionMonitoringService(outputs)
- // HogWatcher on CDP's redis so function health state lands where the API reads it.
- // A sample rate of 0 (default) keeps it fully dormant — no Redis traffic.
- const cdpRedis = createRedisV2PoolFromConfig({
- connection: this.config.CDP_REDIS_HOST
- ? {
- url: this.config.CDP_REDIS_HOST,
- options: { port: this.config.CDP_REDIS_PORT, password: this.config.CDP_REDIS_PASSWORD },
- name: 'logs-cdp-redis',
- }
- : { url: this.config.REDIS_URL, name: 'logs-cdp-redis-fallback' },
- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
+ const logsTransformer = new LogsTransformerService(hogFunctionManager, hogFunctionMonitoring, {
+ siteUrl: this.config.SITE_URL,
+ hogTimeoutMs: this.config.LOGS_TRANSFORMATIONS_HOG_TIMEOUT_MS,
+ messageBudgetMs: this.config.LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS,
+ batchBudgetMs: this.config.LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS,
+ maxErrorLogsPerFunctionPerMessage: this.config.LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION,
})
- const hogWatcher = new HogWatcherService(
- teamManager,
- {
- hogCostTimingLowerMs: this.config.CDP_WATCHER_HOG_COST_TIMING_LOWER_MS,
- hogCostTimingUpperMs: this.config.CDP_WATCHER_HOG_COST_TIMING_UPPER_MS,
- hogCostTiming: this.config.CDP_WATCHER_HOG_COST_TIMING,
- asyncCostTimingLowerMs: this.config.CDP_WATCHER_ASYNC_COST_TIMING_LOWER_MS,
- asyncCostTimingUpperMs: this.config.CDP_WATCHER_ASYNC_COST_TIMING_UPPER_MS,
- asyncCostTiming: this.config.CDP_WATCHER_ASYNC_COST_TIMING,
- sendEvents: this.config.CDP_WATCHER_SEND_EVENTS,
- bucketSize: this.config.CDP_WATCHER_BUCKET_SIZE,
- refillRate: this.config.CDP_WATCHER_REFILL_RATE,
- ttl: this.config.CDP_WATCHER_TTL,
- automaticallyDisableFunctions: this.config.CDP_WATCHER_AUTOMATICALLY_DISABLE_FUNCTIONS,
- thresholdDegraded: this.config.CDP_WATCHER_THRESHOLD_DEGRADED,
- stateLockTtl: this.config.CDP_WATCHER_STATE_LOCK_TTL,
- observeResultsBufferTimeMs: this.config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS,
- observeResultsBufferMaxResults: this.config.CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS,
- },
- cdpRedis
- )
-
- const logsTransformer = new LogsTransformerService(
- hogFunctionManager,
- hogFunctionMonitoring,
- {
- siteUrl: this.config.SITE_URL,
- hogTimeoutMs: this.config.LOGS_TRANSFORMATIONS_HOG_TIMEOUT_MS,
- messageBudgetMs: this.config.LOGS_TRANSFORMATIONS_MESSAGE_BUDGET_MS,
- batchBudgetMs: this.config.LOGS_TRANSFORMATIONS_BATCH_BUDGET_MS,
- maxErrorLogsPerFunctionPerMessage: this.config.LOGS_TRANSFORMATIONS_MAX_ERROR_LOGS_PER_FUNCTION,
- hogWatcherSampleRate: this.config.LOGS_TRANSFORMATIONS_HOG_WATCHER_SAMPLE_RATE,
- },
- hogWatcher
- )
// 4. Logs ingestion consumer
const serviceLoaders: (() => Promise<PluginServerService>)[] = []
diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.ts
index 9e2c76a4f32d..06e6f6405fc3 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts
@@ -75,7 +75,6 @@ describe.each([
encryptedFields: infra.encryptedFields,
integrationManager: infra.integrationManager,
monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
- teamManager: infra.teamManager,
}),
})
jest.spyOn(infra.groupRepository, 'fetchGroup')
diff --git a/nodejs/tests/ingestion/person-updates-e2e.test.ts b/nodejs/tests/ingestion/person-updates-e2e.test.ts
index ef82c4787ade..db39df2c2d21 100644
--- a/nodejs/tests/ingestion/person-updates-e2e.test.ts
+++ b/nodejs/tests/ingestion/person-updates-e2e.test.ts
@@ -246,7 +246,6 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
encryptedFields: infra.encryptedFields,
integrationManager: infra.integrationManager,
monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),
- teamManager: infra.teamManager,
}),
outputs,
clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),