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.

feat(cdp): execute transformations on the rust hogvm behind a config flag (#69605)

José Sequeira4e88b25399d0
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 c9f925648f6c..3247ed9320d6 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -19,6 +19,15 @@ import { propertyFilterPlugin } from '../legacy-plugins/_transformations/propert
import { HogWatcherState } from '../services/monitoring/hog-watcher.service'
import { HogFunctionTemplate } from '../types'
import { HogTransformerService, createHogTransformerService } from './hog-transformer.service'
+import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
+
+jest.mock('@posthog/hogvm-node', () => ({
+ init: jest.fn(),
+ executeBatch: jest.fn(),
+ executeSync: jest.fn(),
+}))
+
+const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
const createPluginEvent = (event: Partial<PluginEvent> = {}, teamId: number = 1): PluginEvent => {
return {
@@ -1944,4 +1953,70 @@ describe('HogTransformer', () => {
expect(result.invocationResults[0].error).toContain('posthogCapture is not supported in transformations')
})
})
+
+ describe('rust vm primary execution', () => {
+ let bytecode: any[]
+
+ beforeEach(async () => {
+ resetHogvmNodeModuleCacheForTests()
+
+ hub.CDP_HOG_RUST_VM_EXECUTION_ENABLED = true
+ hogTransformer = createHogTransformerService(hub, {
+ ...hub,
+ monitoringOutputs: createTestMonitoringOutputs(mockProducer),
+ })
+
+ bytecode = await compileHog(defaultTemplate.code)
+ const hogFunction = createHogFunction({
+ type: 'transformation',
+ name: 'Rust routed',
+ team_id: teamId,
+ enabled: true,
+ bytecode,
+ id: 'bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb',
+ })
+ await insertHogFunction(hub.postgres, teamId, hogFunction)
+ hogTransformer['hogFunctionManager']['onHogFunctionsReloaded'](teamId, [hogFunction.id])
+ })
+
+ it('executes transformations on the rust vm when the flag is enabled', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ {
+ result: { properties: { from_rust: true } },
+ durationUs: 100,
+ logs: [],
+ logsTruncated: false,
+ },
+ ])
+
+ const result = await hogTransformer.transformEventAndProduceMessages(createPluginEvent({}, teamId))
+
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeBatch.mock.calls[0][0]).toEqual(bytecode)
+ expect(result.event?.properties).toEqual({
+ from_rust: true,
+ $transformations_succeeded: ['Rust routed (bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb)'],
+ })
+ })
+
+ it('falls back to the node vm when the rust vm cannot run the program', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ {
+ error: 'Native call failed: unsupported_ext_fn:geoipLookup',
+ durationUs: 100,
+ logs: [],
+ logsTruncated: false,
+ },
+ ])
+
+ const result = await hogTransformer.transformEventAndProduceMessages(createPluginEvent({}, teamId))
+
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ // The node vm ran the real bytecode: the event survives with its original properties.
+ expect(result.event?.properties).toMatchObject({
+ $current_url: 'https://example.com',
+ $transformations_succeeded: ['Rust routed (bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb)'],
+ })
+ })
+ })
})
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 6c92d845b9c9..0455f30273bb 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -30,6 +30,7 @@ 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 { RustVmShadow } from './rust-vm-shadow'
import { getTransformationFunctions } from './transformation-functions'
@@ -37,6 +38,7 @@ export interface HogTransformerConfig {
siteUrl: string
hogWatcherSampleRate: number
hogRustVmShadowSampleRate: number
+ hogRustVmExecutionEnabled: boolean
mmdbFileLocation: string
}
@@ -89,6 +91,7 @@ export class HogTransformerService implements HogTransformer {
private cachedGeoIp?: GeoIp
private cachedTransformationFunctions?: ReturnType<typeof getTransformationFunctions>
private rustVmShadow: RustVmShadow
+ private rustVmExecutor: RustVmExecutor | null
constructor(
private hogFunctionManager: HogFunctionManagerService,
@@ -105,6 +108,9 @@ export class HogTransformerService implements HogTransformer {
sampleRate: config.hogRustVmShadowSampleRate,
mmdbPath: config.mmdbFileLocation,
})
+ this.rustVmExecutor = config.hogRustVmExecutionEnabled
+ ? new RustVmExecutor({ mmdbPath: config.mmdbFileLocation })
+ : null
}
public async start(): Promise<void> {}
@@ -415,6 +421,16 @@ export class HogTransformerService implements HogTransformer {
return await this.pluginExecutor.execute(invocation)
}
+ if (this.rustVmExecutor) {
+ const sensitiveValues = this.hogExecutor.getSensitiveValues(hogFunction, globalsWithInputs.inputs)
+ const rustResult = await this.rustVmExecutor.execute(invocation, sensitiveValues)
+ // Null means the Rust VM can't run this program (addon not built, unsupported host
+ // function): fall through to the Node VM.
+ if (rustResult) {
+ return rustResult
+ }
+ }
+
// Snapshot before execution: later transformations in the chain mutate these globals.
const shadowGlobalsJson = this.rustVmShadow.shouldCapture() ? JSON.stringify(globalsWithInputs) : null
@@ -489,7 +505,13 @@ export class HogTransformerService implements HogTransformer {
* plus the ingestion-specific sample rates from CommonConfig.
*/
export type HogTransformerServiceConfig = CdpCoreServicesConfig &
- Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE' | 'CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE' | 'MMDB_FILE_LOCATION'>
+ Pick<
+ CommonConfig,
+ | 'CDP_HOG_WATCHER_SAMPLE_RATE'
+ | 'CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE'
+ | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED'
+ | 'MMDB_FILE_LOCATION'
+ >
export interface HogTransformerServiceDeps {
geoipService: GeoIPService
@@ -593,6 +615,7 @@ export function createHogTransformerService(
siteUrl: config.SITE_URL,
hogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,
hogRustVmShadowSampleRate: config.CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE,
+ hogRustVmExecutionEnabled: config.CDP_HOG_RUST_VM_EXECUTION_ENABLED,
mmdbFileLocation: config.MMDB_FILE_LOCATION,
}
)
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
new file mode 100644
index 000000000000..af9c912f84e5
--- /dev/null
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
@@ -0,0 +1,115 @@
+import { createExampleInvocation } from '../_tests/fixtures'
+import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
+import { RustVmExecutor } from './rust-vm-executor'
+
+jest.mock('@posthog/hogvm-node', () => ({
+ init: jest.fn(),
+ executeBatch: jest.fn(),
+ executeSync: jest.fn(),
+}))
+
+const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
+
+const rustResult = (overrides: Partial<ReturnType<typeof mockHogvmNode.executeSync>> = {}) => ({
+ result: { properties: { a: 1 } },
+ durationUs: 1500,
+ logs: [],
+ logsTruncated: false,
+ ...overrides,
+})
+
+describe('RustVmExecutor', () => {
+ let executor: RustVmExecutor
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ resetHogvmNodeModuleCacheForTests()
+ executor = new RustVmExecutor({ mmdbPath: '/dev/null' })
+ })
+
+ it('executes the invocation bytecode against its globals off the JS thread and returns a finished result', async () => {
+ const invocation = createExampleInvocation({ bytecode: ['_H', 1, 38] })
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult()])
+
+ const result = await executor.execute(invocation, [])
+
+ // executeBatch runs as a napi AsyncTask off the event loop — the sync
+ // entry point must not be used on the ingestion hot path.
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledWith(['_H', 1, 38], [invocation.state.globals], {
+ maxSteps: 1_000_000,
+ })
+ expect(mockHogvmNode.executeSync).not.toHaveBeenCalled()
+ expect(result).not.toBeNull()
+ expect(result!.finished).toEqual(true)
+ expect(result!.error).toBeUndefined()
+ expect(result!.execResult).toEqual({ properties: { a: 1 } })
+ expect(result!.invocation.state.timings).toEqual([{ kind: 'hog', duration_ms: 1.5 }])
+ expect(result!.logs.map((log) => log.message)).toEqual(['Function completed in 1.5ms.'])
+ })
+
+ it('a null program result leaves execResult unset so the transformer drops the event', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult({ result: null })])
+
+ const result = await executor.execute(createExampleInvocation(), [])
+
+ expect(result!.error).toBeUndefined()
+ expect(result!.execResult).toBeUndefined()
+ })
+
+ it('surfaces print() output as info logs with sensitive values redacted, plus a truncation warning', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ rustResult({ logs: ['token is secret-token', 'plain'], logsTruncated: true }),
+ ])
+
+ const result = await executor.execute(createExampleInvocation(), ['secret-token'])
+
+ expect(result!.logs.map((log) => [log.level, log.message])).toEqual([
+ ['info', 'token is ***REDACTED***'],
+ ['info', 'plain'],
+ ['warn', expect.stringContaining('Function exceeded maximum log entries')],
+ ['debug', expect.stringContaining('Function completed in')],
+ ])
+ })
+
+ it("redacts each invocation's logs with its own sensitive values, not another invocation's", async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult({ logs: ['token is secret-a and secret-b'] })])
+
+ const first = await executor.execute(createExampleInvocation(), ['secret-a'])
+ const second = await executor.execute(createExampleInvocation(), ['secret-b'])
+
+ expect(first!.logs[0].message).toEqual('token is ***REDACTED*** and secret-b')
+ expect(second!.logs[0].message).toEqual('token is secret-a and ***REDACTED***')
+ })
+
+ it('a rust execution error becomes the result error with an error log, without falling back', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult({ result: undefined, error: 'Division by zero' })])
+
+ const result = await executor.execute(createExampleInvocation(), [])
+
+ expect(result).not.toBeNull()
+ expect(result!.error).toEqual('Division by zero')
+ expect(result!.finished).toEqual(true)
+ expect(result!.execResult).toBeUndefined()
+ expect(result!.logs.map((log) => log.level)).toEqual(['error'])
+ expect(result!.logs[0].message).toContain('Division by zero')
+ })
+
+ it.each([
+ ['unsupported host function', 'Native call failed: unsupported_ext_fn:geoipLookup'],
+ ['function missing from the rust vm', 'Unknown function sendEmail'],
+ ['global chain the rust vm cannot resolve', 'Unknown Global ["inputs", "foo"]'],
+ ])('falls back to the node vm on %s', async (_name, error) => {
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult({ result: undefined, error })])
+
+ await expect(executor.execute(createExampleInvocation(), [])).resolves.toBeNull()
+ })
+
+ it('falls back to the node vm when the native addon is unavailable', async () => {
+ mockHogvmNode.init.mockImplementation(() => {
+ throw new Error('addon not built')
+ })
+
+ await expect(executor.execute(createExampleInvocation(), [])).resolves.toBeNull()
+ expect(mockHogvmNode.executeBatch).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
new file mode 100644
index 000000000000..ce802f79fdd3
--- /dev/null
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
@@ -0,0 +1,103 @@
+import { DateTime } from 'luxon'
+import { Counter, Histogram } from 'prom-client'
+
+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
+import { createAddLogFunction, sanitizeLogMessage } from '../utils'
+import { createInvocationResult } from '../utils/invocation-utils'
+import { HogvmNodeModule, RUST_MAX_STEPS, isUnsupportedByRustVm, loadHogvmNodeModule } from './rust-vm'
+
+/**
+ * Executes transformation invocations on the Rust HogVM (via the `@posthog/hogvm-node` napi
+ * addon) as the primary executor, producing the same `CyclotronJobInvocationResult` shape the
+ * Node executor does. Invocations the Rust VM can't run — the addon isn't built, or the program
+ * calls a host function the binding doesn't implement — return null so the caller falls back to
+ * the Node VM.
+ */
+
+export const rustVmExecution = new Counter({
+ name: 'hogvm_rust_execution_total',
+ help: 'Outcomes of transformation executions where the Rust HogVM is the primary executor',
+ labelNames: ['outcome'],
+})
+
+export const rustVmExecutionDuration = new Histogram({
+ name: 'hogvm_rust_execution_duration_ms',
+ help: 'Per-invocation hog execution duration on the Rust HogVM as the primary executor',
+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 100],
+})
+
+export class RustVmExecutor {
+ constructor(private options: { mmdbPath: string }) {}
+
+ private getModule(): HogvmNodeModule | null {
+ return loadHogvmNodeModule({ mmdbPath: this.options.mmdbPath })
+ }
+
+ /**
+ * Execute one transformation invocation on the Rust VM. Returns null when the Node VM must
+ * run it instead.
+ *
+ * Runs through `executeBatch` (a napi AsyncTask on the libuv worker pool), NOT `executeSync`:
+ * the step budget bounds total work, but a costly program running synchronously would
+ * monopolize the ingestion worker's JS thread, bypassing the wall-clock limiting and
+ * event-loop yielding the Node path has. Concurrent events therefore execute in parallel on
+ * worker threads; batching many events into one call (rayon fan-out) is a possible follow-up.
+ */
+ public async execute(
+ invocation: CyclotronJobInvocationHogFunction,
+ sensitiveValues: string[]
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null> {
+ const module_ = this.getModule()
+ if (!module_) {
+ rustVmExecution.inc({ outcome: 'fallback_unavailable' })
+ return null
+ }
+
+ const [rust] = await module_.executeBatch(invocation.hogFunction.bytecode, [invocation.state.globals], {
+ maxSteps: RUST_MAX_STEPS,
+ })
+ if (!rust) {
+ rustVmExecution.inc({ outcome: 'fallback_unavailable' })
+ return null
+ }
+
+ if (rust.error && isUnsupportedByRustVm(rust.error)) {
+ rustVmExecution.inc({ outcome: 'fallback_unsupported' })
+ return null
+ }
+
+ const durationMs = rust.durationUs / 1000
+ rustVmExecutionDuration.observe(durationMs)
+
+ const result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation)
+ const addLog = createAddLogFunction(result.logs)
+ result.invocation.state.timings.push({ kind: 'hog', duration_ms: durationMs })
+
+ const eventId = invocation.state.globals.event?.uuid || 'Unknown event'
+
+ for (const message of rust.logs ?? []) {
+ result.logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: sanitizeLogMessage([message], sensitiveValues),
+ })
+ }
+ if (rust.logsTruncated) {
+ addLog('warn', `Function exceeded maximum log entries. No more logs will be collected. Event: ${eventId}`)
+ }
+
+ if (rust.error) {
+ rustVmExecution.inc({ outcome: 'error' })
+ addLog('error', `Error executing function on event ${eventId}: ${rust.error}`)
+ result.error = rust.error
+ return result
+ }
+
+ rustVmExecution.inc({ outcome: 'executed' })
+ if (rust.result) {
+ result.execResult = rust.result
+ }
+ addLog('debug', `Function completed in ${Number(durationMs.toFixed(2))}ms.`)
+ return result
+ }
+}
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
index bed982887fc1..1f6d98a1dc1b 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
@@ -84,7 +84,7 @@ describe('RustVmShadow', () => {
[
'host function missing from the rust vm',
finishedNode({}),
- { error: 'Unknown Global sendEmail', durationUs: 1 },
+ { error: 'Unknown function sendEmail', durationUs: 1 },
'skipped_unsupported',
],
['missing rust result', finishedNode({}), undefined, 'rust_error'],
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
index 64cbb0058a56..dbc1641c7840 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
@@ -5,7 +5,7 @@ import { HogBytecode } from '~/cdp/types'
import { parseJSON } from '~/common/utils/json-parse'
import { logger } from '~/common/utils/logger'
-import { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'
+import { HogvmNodeModule, RUST_MAX_STEPS, RustExecResult, isUnsupportedByRustVm, loadHogvmNodeModule } from './rust-vm'
/**
* Shadow-executes sampled transformation invocations on the Rust HogVM (via the
@@ -18,9 +18,6 @@ import { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'
* itself.
*/
-// The Rust VM budgets steps, not wall-clock time; generous so it never trips before the Node VM's
-// timeout would.
-const RUST_MAX_STEPS = 1_000_000
// STL functions whose output legitimately differs between two executions — programs calling them
// can never be compared, so they're skipped at capture time.
const NONDETERMINISTIC_FNS = new Set(['randomFloat', 'generateUUIDv4', 'now', 'today'])
@@ -81,30 +78,13 @@ export interface ShadowCapturedInvocation {
node: ShadowNodeResult
}
-interface RustExecResult {
- result?: unknown
- error?: string
- durationUs: number
-}
-
-interface HogvmNodeModule {
- init(options: { mmdbPath?: string; knownBotUaList?: string[]; knownBotIpList?: string[] }): void
- executeBatch(
- program: unknown[],
- events: unknown[],
- options?: { parallel?: boolean; maxSteps?: number }
- ): Promise<RustExecResult[]>
-}
-
export function classifyShadowOutcome(node: ShadowNodeResult, rust: RustExecResult | undefined): ShadowOutcome {
if (!rust) {
return 'rust_error'
}
if (rust.error) {
// Host functions the rust binding doesn't implement — not comparable, not a divergence.
- // 'Unknown Global <name>' is the rust VM's exact error for calling a function it doesn't
- // know; anchored to the prefix so other errors mentioning the words can't be swallowed.
- if (rust.error.includes('unsupported_ext_fn:') || rust.error.startsWith('Unknown Global ')) {
+ if (isUnsupportedByRustVm(rust.error)) {
return 'skipped_unsupported'
}
// Both VMs failed the program: they agree.
@@ -268,20 +248,9 @@ export class RustVmShadow {
this.module_ = null
return null
}
- try {
- const module_: HogvmNodeModule = require('@posthog/hogvm-node')
- module_.init({
- mmdbPath: this.options.mmdbPath,
- knownBotUaList: KNOWN_BOT_UA_LIST,
- knownBotIpList: KNOWN_BOT_IP_LIST,
- })
- this.module_ = module_
+ this.module_ = loadHogvmNodeModule({ mmdbPath: this.options.mmdbPath })
+ if (this.module_) {
logger.info('🦀', 'Rust HogVM shadow mode enabled', { sampleRate: this.options.sampleRate })
- } catch (error) {
- this.module_ = null
- logger.warn('🦀', 'Rust HogVM native module unavailable, shadow mode disabled', {
- error: String(error),
- })
}
return this.module_
}
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm.ts b/nodejs/src/cdp/hog-transformations/rust-vm.ts
new file mode 100644
index 000000000000..3deb06eab314
--- /dev/null
+++ b/nodejs/src/cdp/hog-transformations/rust-vm.ts
@@ -0,0 +1,87 @@
+import { logger } from '~/common/utils/logger'
+
+import { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'
+
+/**
+ * Shared access to the `@posthog/hogvm-node` napi addon (the Rust HogVM). The addon is optional —
+ * when it isn't built for this environment, `loadHogvmNodeModule` returns null and callers fall
+ * back to the Node VM.
+ */
+
+// The Rust VM budgets steps, not wall-clock time; generous so it never trips before the Node VM's
+// timeout would.
+export const RUST_MAX_STEPS = 1_000_000
+
+// Error formats that mean "the Rust VM can't run this program" rather than "the program failed".
+// All three are contracts with the Rust side, pinned by tests there — don't change one without the
+// other: the binding's ext_fns fail unimplemented host functions with the `unsupported_ext_fn:`
+// prefix (rust/common/hogvm/node/src/ext_fns.rs `unsupported()`); the hogvm crate reports calls to
+// functions it doesn't know at all as `Unknown function <name>` and unresolvable global chains as
+// `Unknown Global <chain>`.
+export const UNSUPPORTED_EXT_FN_ERROR = 'unsupported_ext_fn:'
+export const UNKNOWN_FUNCTION_ERROR_PREFIX = 'Unknown function '
+export const UNKNOWN_GLOBAL_ERROR_PREFIX = 'Unknown Global '
+
+/**
+ * True when the error means the Rust VM can't run this program (the Node VM can). The executor
+ * uses this to hand the invocation to the Node VM; the shadow uses it to classify the comparison
+ * as skipped rather than as a divergence. Real execution errors must never match — the caller
+ * would otherwise run the program twice.
+ */
+export function isUnsupportedByRustVm(error: string): boolean {
+ return (
+ error.includes(UNSUPPORTED_EXT_FN_ERROR) ||
+ error.startsWith(UNKNOWN_FUNCTION_ERROR_PREFIX) ||
+ error.startsWith(UNKNOWN_GLOBAL_ERROR_PREFIX)
+ )
+}
+
+export interface RustExecResult {
+ result?: unknown
+ error?: string
+ durationUs: number
+ /** Messages from print() calls, in call order, capped at 24 entries. */
+ logs?: string[]
+ /** True when print() was called past the cap and messages were dropped. */
+ logsTruncated?: boolean
+}
+
+export interface HogvmNodeModule {
+ init(options: { mmdbPath?: string; knownBotUaList?: string[]; knownBotIpList?: string[] }): void
+ executeBatch(
+ program: unknown[],
+ events: unknown[],
+ options?: { parallel?: boolean; maxSteps?: number }
+ ): Promise<RustExecResult[]>
+ executeSync(program: unknown[], globals: unknown, options?: { maxSteps?: number }): RustExecResult
+}
+
+let cachedModule: HogvmNodeModule | null | undefined = undefined
+
+/**
+ * Load and initialize the native addon once per process (`init` is idempotent on the Rust side).
+ * Returns null when the addon isn't built for this environment. `options` only take effect on the
+ * first call in the process — later callers always get the module as first configured.
+ */
+export function loadHogvmNodeModule(options: { mmdbPath: string }): HogvmNodeModule | null {
+ if (cachedModule !== undefined) {
+ return cachedModule
+ }
+ try {
+ const module_: HogvmNodeModule = require('@posthog/hogvm-node')
+ module_.init({
+ mmdbPath: options.mmdbPath,
+ knownBotUaList: KNOWN_BOT_UA_LIST,
+ knownBotIpList: KNOWN_BOT_IP_LIST,
+ })
+ cachedModule = module_
+ } catch (error) {
+ cachedModule = null
+ logger.warn('🦀', 'Rust HogVM native module unavailable', { error: String(error) })
+ }
+ return cachedModule
+}
+
+export function resetHogvmNodeModuleCacheForTests(): void {
+ cachedModule = undefined
+}
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 432a57a35930..82144cb7a065 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -191,6 +191,10 @@ export type CommonConfig = BaseServerConfig & {
// latency/correctness comparison; the Node VM result stays authoritative
CDP_HOG_RUST_VM_SHADOW_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
+
// Event loop yield helper (yieldEventLoopIfNeeded)
EVENT_LOOP_YIELD_THRESHOLD_MS: number
}
@@ -362,6 +366,7 @@ export function getDefaultCommonConfig(): CommonConfig {
// Shared between ingestion and CDP
CDP_HOG_WATCHER_SAMPLE_RATE: 0,
CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE: 0,
+ CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
// Event loop yield helper
EVENT_LOOP_YIELD_THRESHOLD_MS: 200,
diff --git a/rust/common/hogvm/node/index.d.ts b/rust/common/hogvm/node/index.d.ts
index a0a2bc83d498..00fc07386868 100644
--- a/rust/common/hogvm/node/index.d.ts
+++ b/rust/common/hogvm/node/index.d.ts
@@ -12,6 +12,10 @@ export interface HogExecResult {
result?: unknown
error?: string
durationUs: number
+ /** Messages from print() calls, in call order, capped at 24 entries. */
+ logs?: string[]
+ /** True when print() was called past the cap and messages were dropped. */
+ logsTruncated?: boolean
}
export interface ExecuteBatchOptions {
@@ -21,6 +25,11 @@ export interface ExecuteBatchOptions {
maxSteps?: number
}
+export interface ExecuteSyncOptions {
+ /** Step budget for the execution (the Rust VM has no wall-clock timeout). */
+ maxSteps?: number
+}
+
/**
* Load process-wide state for the transformation host functions. Idempotent; only the first call
* takes effect.
@@ -36,3 +45,10 @@ export function executeBatch(
events: unknown[],
options?: ExecuteBatchOptions
): Promise<HogExecResult[]>
+
+/**
+ * Run one Hog program against one event-globals synchronously on the calling thread. This is the
+ * primary-execution path for ingestion transformations: it matches the Node VM's synchronous
+ * exec, with no threadpool round-trip.
+ */
+export function executeSync(program: unknown[], globals: unknown, options?: ExecuteSyncOptions): HogExecResult
diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rs
index c3ff264aee8c..24d0c96c849b 100644
--- a/rust/common/hogvm/node/src/exec.rs
+++ b/rust/common/hogvm/node/src/exec.rs
@@ -8,6 +8,7 @@ use rayon::prelude::*;
use serde_json::Value;
use crate::ext_fns::transformation_ext_fns;
+use crate::logs;
const PARALLEL_CHUNK_SIZE: usize = 500;
@@ -21,6 +22,10 @@ pub struct HogExecResult {
pub result: Option<Value>,
pub error: Option<String>,
pub duration_us: f64,
+ /// Messages from `print()` calls, in call order, capped at `logs::MAX_CAPTURED_LOGS`.
+ pub logs: Vec<String>,
+ /// True when `print()` was called past the cap and messages were dropped.
+ pub logs_truncated: bool,
}
pub fn run_batch(
@@ -73,16 +78,26 @@ fn run_chunk(tokens: &[Value], chunk: &[Value], max_steps: Option<usize>) -> Vec
.iter()
.map(|event| {
ctx.set_globals(event.clone());
+ logs::reset();
let start = Instant::now();
let outcome = sync_execute(&ctx, false);
let duration_us = start.elapsed().as_secs_f64() * 1_000_000.0;
+ let (captured_logs, logs_truncated) = logs::take();
match outcome {
Ok(value) => HogExecResult {
result: Some(value),
error: None,
duration_us,
+ logs: captured_logs,
+ logs_truncated,
+ },
+ Err(failure) => HogExecResult {
+ result: None,
+ error: Some(failure.error.to_string()),
+ duration_us,
+ logs: captured_logs,
+ logs_truncated,
},
- Err(failure) => error_result(&failure.error.to_string(), duration_us),
}
})
.collect()
@@ -93,6 +108,8 @@ fn error_result(error: &str, duration_us: f64) -> HogExecResult {
result: None,
error: Some(error.to_string()),
duration_us,
+ logs: Vec::new(),
+ logs_truncated: false,
}
}
@@ -274,8 +291,33 @@ mod tests {
.contains("unsupported_ext_fn:geoipLookup"));
}
+ // Pins the hogvm crate's error formats the Node callers (rust-vm.ts isUnsupportedByRustVm)
+ // match on to fall back to the Node VM: `Unknown function <name>` for calling a function the
+ // VM doesn't know, `Unknown Global <chain>` for an unresolvable global chain.
+ #[test]
+ fn unknown_name_error_prefixes_are_the_node_fallback_contract() {
+ let results = run_batch(
+ &call_fn_program("someFunctionNobodyImplements", "x"),
+ &[json!({})],
+ false,
+ None,
+ );
+ assert!(results[0]
+ .error
+ .as_deref()
+ .unwrap()
+ .starts_with("Unknown function "));
+
+ let results = run_batch(&get_global_program("missing"), &[json!({})], false, None);
+ assert!(results[0]
+ .error
+ .as_deref()
+ .unwrap()
+ .starts_with("Unknown Global "));
+ }
+
#[test]
- fn print_is_a_noop_and_execution_continues() {
+ fn print_is_captured_as_a_log_and_execution_continues() {
// print("x") (POP the call result), then return 1+2
let mut program = vec![
json!("_H"),
@@ -291,6 +333,90 @@ mod tests {
let results = run_batch(&program, &[json!({})], false, None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].result, Some(json!(3)));
+ assert_eq!(results[0].logs, vec!["x".to_string()]);
+ assert!(!results[0].logs_truncated);
+ }
+
+ // print(globals.g) — non-string args are JSON-serialized like the Node executor's handler.
+ #[test]
+ fn print_serializes_non_string_args_and_does_not_leak_across_events() {
+ let program = vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!("g"),
+ json!(1),
+ json!(1),
+ json!(2),
+ json!("print"),
+ json!(1),
+ json!(38),
+ ];
+ let events = vec![json!({ "g": { "a": 1 } }), json!({ "g": "plain" })];
+ let results = run_batch(&program, &events, false, None);
+ assert_eq!(results[0].logs, vec![r#"{"a":1}"#.to_string()]);
+ assert_eq!(results[1].logs, vec!["plain".to_string()]);
+ }
+
+ // print(globals.g) (POP), then return 1+2 — the marker only surfaces through the log buffer.
+ fn print_global_program(name: &str) -> Vec<Value> {
+ let mut program = vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!(name),
+ json!(1),
+ json!(1),
+ json!(2),
+ json!("print"),
+ json!(1),
+ json!(35),
+ ];
+ program.extend(add_program().into_iter().skip(2));
+ program
+ }
+
+ #[test]
+ fn parallel_execution_does_not_mix_print_logs_across_events() {
+ // Enough events for several PARALLEL_CHUNK_SIZE chunks spread over rayon workers.
+ let events: Vec<Value> = (0..1500)
+ .map(|i| json!({ "g": format!("marker-{i}") }))
+ .collect();
+ let results = run_batch(&print_global_program("g"), &events, true, None);
+ assert_eq!(results.len(), events.len());
+ for (i, r) in results.iter().enumerate() {
+ assert_eq!(r.error, None);
+ assert_eq!(r.logs, vec![format!("marker-{i}")]);
+ assert!(!r.logs_truncated);
+ }
+ }
+
+ #[test]
+ fn print_logs_are_capped_and_flagged_truncated() {
+ // A loop would need more opcodes; just chain MAX_CAPTURED_LOGS + 1 print calls.
+ let mut program = vec![json!("_H"), json!(1)];
+ for _ in 0..(crate::logs::MAX_CAPTURED_LOGS + 1) {
+ program.extend([
+ json!(32),
+ json!("m"),
+ json!(2),
+ json!("print"),
+ json!(1),
+ json!(35),
+ ]);
+ }
+ program.extend(add_program().into_iter().skip(2));
+ let results = run_batch(&program, &[json!({})], false, None);
+ assert_eq!(results[0].error, None);
+ assert_eq!(results[0].logs.len(), crate::logs::MAX_CAPTURED_LOGS);
+ assert!(results[0].logs_truncated);
+
+ // Sequential run_batch executes on the calling thread — the same thread-local buffer the
+ // truncating execution above just used. Nothing may carry over into the next execution
+ // (this is the back-to-back executeSync shape of the primary path).
+ let results = run_batch(&add_program(), &[json!({})], false, None);
+ assert_eq!(results[0].logs, Vec::<String>::new());
+ assert!(!results[0].logs_truncated);
}
#[test]
diff --git a/rust/common/hogvm/node/src/ext_fns.rs b/rust/common/hogvm/node/src/ext_fns.rs
index 88d926cb8abf..243b2dfc0f46 100644
--- a/rust/common/hogvm/node/src/ext_fns.rs
+++ b/rust/common/hogvm/node/src/ext_fns.rs
@@ -9,6 +9,7 @@ use hogvm::{construct_free_standing, native_func, HogLiteral, NativeFunction, Vm
use serde_json::Value;
use crate::geoip;
+use crate::logs;
static BOT_UA_LIST: OnceLock<Vec<String>> = OnceLock::new();
static BOT_IP_LIST: OnceLock<Vec<String>> = OnceLock::new();
@@ -34,6 +35,10 @@ pub fn set_bot_lists_for_tests() {
);
}
+// The `unsupported_ext_fn:` prefix is a contract with the Node callers
+// (nodejs/src/cdp/hog-transformations/rust-vm.ts `isUnsupportedByRustVm`): it makes the executor
+// hand the invocation to the Node VM and the shadow classify the comparison as skipped. Rephrasing
+// it would turn those fallbacks into hard failures — change both sides together.
pub fn unsupported(name: &str) -> VmError {
VmError::NativeCallFailed(format!("unsupported_ext_fn:{name}"))
}
@@ -44,9 +49,23 @@ pub fn transformation_ext_fns() -> HashMap<String, NativeFunction> {
.get_or_init(|| {
let mut fns: HashMap<String, NativeFunction> = HashMap::new();
+ // Mirrors the Node executor's print handler: string args pass through, everything
+ // else is JSON-serialized, joined with ", ".
fns.insert(
"print".to_string(),
- native_func(|_vm, _args| Ok(HogLiteral::Null.into())),
+ native_func(|vm, args| {
+ let mut parts: Vec<String> = Vec::with_capacity(args.len());
+ for arg in &args {
+ let part = match arg.deref(&vm.heap)? {
+ HogLiteral::String(value) => value.clone(),
+ _ => serde_json::to_string(&vm.hog_to_json(arg)?)
+ .map_err(|e| VmError::NativeCallFailed(e.to_string()))?,
+ };
+ parts.push(part);
+ }
+ logs::push(parts.join(", "));
+ Ok(HogLiteral::Null.into())
+ }),
);
fns.insert(
diff --git a/rust/common/hogvm/node/src/lib.rs b/rust/common/hogvm/node/src/lib.rs
index e9faca50cad4..469968345aff 100644
--- a/rust/common/hogvm/node/src/lib.rs
+++ b/rust/common/hogvm/node/src/lib.rs
@@ -1,9 +1,10 @@
-//! Rust HogVM exposed to Node via napi-rs, for shadow execution of ingestion transformations.
+//! Rust HogVM exposed to Node via napi-rs, for executing ingestion transformations.
//!
-//! The Node VM stays authoritative; this binding runs the same (bytecode, globals) pairs on the
-//! Rust VM so the caller can compare latency and correctness. `executeBatch` crosses the FFI
-//! boundary once per batch, runs off the JS event loop (libuv worker via `AsyncTask`), and can fan
-//! out over a rayon thread pool.
+//! Two entry points: `executeSync` runs one (bytecode, globals) pair on the calling thread — the
+//! primary-execution path, equivalent to the Node VM's synchronous exec. `executeBatch` crosses
+//! the FFI boundary once per batch, runs off the JS event loop (libuv worker via `AsyncTask`), and
+//! can fan out over a rayon thread pool — the shadow-comparison path, where the Node VM stays
+//! authoritative and results are only compared.
//!
//! Transformation host functions (`geoipLookup`, `cleanNullValues`, `isKnownBotUserAgent`,
//! `isKnownBotIp`) mirror `nodejs/src/cdp/hog-transformations/transformation-functions.ts`; call
@@ -14,6 +15,7 @@
mod exec;
mod ext_fns;
mod geoip;
+mod logs;
#[cfg(not(feature = "noop"))]
use napi::bindgen_prelude::AsyncTask;
@@ -21,7 +23,6 @@ use napi::Result as NapiResult;
#[cfg(not(feature = "noop"))]
use napi::{Env, Task};
use napi_derive::napi;
-#[cfg(not(feature = "noop"))]
use serde_json::Value;
pub use exec::{run_batch, HogExecResult};
@@ -102,3 +103,29 @@ pub fn execute_batch(
max_steps: options.max_steps.map(|m| m as usize),
})
}
+
+#[napi(object)]
+pub struct ExecuteSyncOptions {
+ /// Step budget for the execution (the Rust VM has no wall-clock timeout).
+ pub max_steps: Option<u32>,
+}
+
+/// Run one Hog program against one event-globals synchronously on the calling thread. This is the
+/// primary-execution path for ingestion transformations: it matches the Node VM's synchronous
+/// exec, with no threadpool round-trip.
+#[napi]
+pub fn execute_sync(
+ program: Value,
+ globals: Value,
+ options: Option<ExecuteSyncOptions>,
+) -> HogExecResult {
+ let tokens = match program {
+ Value::Array(tokens) => tokens,
+ _ => Vec::new(),
+ };
+ let max_steps = options.and_then(|o| o.max_steps).map(|m| m as usize);
+ run_batch(&tokens, std::slice::from_ref(&globals), false, max_steps)
+ .into_iter()
+ .next()
+ .expect("run_batch returns one result per event")
+}
diff --git a/rust/common/hogvm/node/src/logs.rs b/rust/common/hogvm/node/src/logs.rs
new file mode 100644
index 000000000000..872435681f51
--- /dev/null
+++ b/rust/common/hogvm/node/src/logs.rs
@@ -0,0 +1,56 @@
+//! Per-event capture of `print()` output.
+//!
+//! The `print` host function has no way to reach the result being built for the current event, so
+//! it writes to a thread-local buffer instead. An event executes entirely on one thread (the JS
+//! thread for `executeSync`, a rayon worker for `executeBatch`), so resetting the buffer before
+//! each execution and draining it right after cannot mix events up.
+
+use std::cell::RefCell;
+
+// The Node executor stops collecting print logs after 24 entries (MAX_HOG_LOGS = 25, the 25th
+// call becomes a "too many logs" warning).
+pub const MAX_CAPTURED_LOGS: usize = 24;
+
+struct LogBuffer {
+ messages: Vec<String>,
+ truncated: bool,
+}
+
+thread_local! {
+ static LOG_BUFFER: RefCell<LogBuffer> = const {
+ RefCell::new(LogBuffer {
+ messages: Vec::new(),
+ truncated: false,
+ })
+ };
+}
+
+pub fn reset() {
+ LOG_BUFFER.with(|buffer| {
+ let mut buffer = buffer.borrow_mut();
+ buffer.messages.clear();
+ buffer.truncated = false;
+ });
+}
+
+pub fn push(message: String) {
+ LOG_BUFFER.with(|buffer| {
+ let mut buffer = buffer.borrow_mut();
+ if buffer.messages.len() >= MAX_CAPTURED_LOGS {
+ buffer.truncated = true;
+ } else {
+ buffer.messages.push(message);
+ }
+ });
+}
+
+/// Drain the current thread's buffer, returning the captured messages and whether any were
+/// dropped past the cap.
+pub fn take() -> (Vec<String>, bool) {
+ LOG_BUFFER.with(|buffer| {
+ let mut buffer = buffer.borrow_mut();
+ let truncated = buffer.truncated;
+ buffer.truncated = false;
+ (std::mem::take(&mut buffer.messages), truncated)
+ })
+}