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): run the rust hogvm synchronously and remove the shadow comparison (#70070)

José Sequeira77113463eba8
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 3247ed9320d6..0e780241217d 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -23,7 +23,6 @@ import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
jest.mock('@posthog/hogvm-node', () => ({
init: jest.fn(),
- executeBatch: jest.fn(),
executeSync: jest.fn(),
}))
@@ -1980,19 +1979,17 @@ describe('HogTransformer', () => {
})
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,
- },
- ])
+ mockHogvmNode.executeSync.mockReturnValue({
+ 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(mockHogvmNode.executeSync).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeSync.mock.calls[0][0]).toEqual(bytecode)
expect(result.event?.properties).toEqual({
from_rust: true,
$transformations_succeeded: ['Rust routed (bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb)'],
@@ -2000,18 +1997,16 @@ describe('HogTransformer', () => {
})
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,
- },
- ])
+ mockHogvmNode.executeSync.mockReturnValue({
+ 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)
+ expect(mockHogvmNode.executeSync).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',
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 0455f30273bb..ebb7dc37dfc7 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -31,13 +31,11 @@ import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '..
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'
export interface HogTransformerConfig {
siteUrl: string
hogWatcherSampleRate: number
- hogRustVmShadowSampleRate: number
hogRustVmExecutionEnabled: boolean
mmdbFileLocation: string
}
@@ -90,7 +88,6 @@ export class HogTransformerService implements HogTransformer {
private invocationResults: CyclotronJobInvocationResult[] = []
private cachedGeoIp?: GeoIp
private cachedTransformationFunctions?: ReturnType<typeof getTransformationFunctions>
- private rustVmShadow: RustVmShadow
private rustVmExecutor: RustVmExecutor | null
constructor(
@@ -104,10 +101,6 @@ export class HogTransformerService implements HogTransformer {
private redis: RedisV2,
private config: HogTransformerConfig
) {
- this.rustVmShadow = new RustVmShadow({
- sampleRate: config.hogRustVmShadowSampleRate,
- mmdbPath: config.mmdbFileLocation,
- })
this.rustVmExecutor = config.hogRustVmExecutionEnabled
? new RustVmExecutor({ mmdbPath: config.mmdbFileLocation })
: null
@@ -143,8 +136,6 @@ export class HogTransformerService implements HogTransformer {
shouldRunHogWatcher
? mirrorCall('hog-watcher.observeResults', () => this.hogWatcherMirror?.observeResults(results))
: Promise.resolve(),
-
- mirrorCall('hogvm.rust-shadow-flush', () => this.rustVmShadow.flush(), 5000),
])
}
@@ -423,7 +414,7 @@ export class HogTransformerService implements HogTransformer {
if (this.rustVmExecutor) {
const sensitiveValues = this.hogExecutor.getSensitiveValues(hogFunction, globalsWithInputs.inputs)
- const rustResult = await this.rustVmExecutor.execute(invocation, sensitiveValues)
+ const rustResult = 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) {
@@ -431,33 +422,10 @@ export class HogTransformerService implements HogTransformer {
}
}
- // Snapshot before execution: later transformations in the chain mutate these globals.
- const shadowGlobalsJson = this.rustVmShadow.shouldCapture() ? JSON.stringify(globalsWithInputs) : null
-
- const result = await this.hogExecutor.execute(invocation, {
+ return await this.hogExecutor.execute(invocation, {
functions: transformationFunctions,
asyncFunctionsNames: [],
})
-
- if (shadowGlobalsJson) {
- this.rustVmShadow.capture({
- functionId: hogFunction.id,
- teamId: hogFunction.team_id,
- bytecode: hogFunction.bytecode,
- globalsJson: shadowGlobalsJson,
- node: {
- finished: result.finished,
- error: result.error != null ? String(result.error) : undefined,
- // Snapshot: the transformer mutates execResult right after this returns.
- execResultJson: result.execResult !== undefined ? JSON.stringify(result.execResult) : null,
- durationMs: result.invocation.state.timings
- .filter((timing) => timing.kind === 'hog')
- .reduce((sum, timing) => sum + timing.duration_ms, 0),
- },
- })
- }
-
- return result
}
public async fetchAndCacheHogFunctionStates(functionIds: string[]): Promise<void> {
@@ -505,13 +473,7 @@ 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'
- | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED'
- | 'MMDB_FILE_LOCATION'
- >
+ Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE' | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED' | 'MMDB_FILE_LOCATION'>
export interface HogTransformerServiceDeps {
geoipService: GeoIPService
@@ -614,7 +576,6 @@ 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
index f4eb4dbd7dc5..a04d0848d0d1 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
@@ -6,7 +6,6 @@ import { RustVmExecutor } from './rust-vm-executor'
jest.mock('@posthog/hogvm-node', () => ({
init: jest.fn(),
- executeBatch: jest.fn(),
executeSync: jest.fn(),
}))
@@ -29,18 +28,15 @@ describe('RustVmExecutor', () => {
executor = new RustVmExecutor({ mmdbPath: '/dev/null' })
})
- it('executes the invocation bytecode against its globals off the JS thread and returns a finished result', async () => {
+ it('executes the invocation bytecode against its globals and returns a finished result', () => {
const invocation = createExampleInvocation({ bytecode: ['_H', 1, 38] })
- mockHogvmNode.executeBatch.mockResolvedValue([rustResult()])
+ mockHogvmNode.executeSync.mockReturnValue(rustResult())
- const result = await executor.execute(invocation, [])
+ const result = 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], {
+ expect(mockHogvmNode.executeSync).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()
@@ -49,21 +45,21 @@ describe('RustVmExecutor', () => {
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 })])
+ it('a null program result leaves execResult unset so the transformer drops the event', () => {
+ mockHogvmNode.executeSync.mockReturnValue(rustResult({ result: null }))
- const result = await executor.execute(createExampleInvocation(), [])
+ const result = 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 }),
- ])
+ it('surfaces print() output as info logs with sensitive values redacted, plus a truncation warning', () => {
+ mockHogvmNode.executeSync.mockReturnValue(
+ rustResult({ logs: ['token is secret-token', 'plain'], logsTruncated: true })
+ )
- const result = await executor.execute(createExampleInvocation(), ['secret-token'])
+ const result = executor.execute(createExampleInvocation(), ['secret-token'])
expect(result!.logs.map((log) => [log.level, log.message])).toEqual([
['info', 'token is ***REDACTED***'],
@@ -73,20 +69,20 @@ describe('RustVmExecutor', () => {
])
})
- 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'] })])
+ it("redacts each invocation's logs with its own sensitive values, not another invocation's", () => {
+ mockHogvmNode.executeSync.mockReturnValue(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'])
+ const first = executor.execute(createExampleInvocation(), ['secret-a'])
+ const second = 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' })])
+ it('a rust execution error becomes the result error with an error log, without falling back', () => {
+ mockHogvmNode.executeSync.mockReturnValue(rustResult({ result: undefined, error: 'Division by zero' }))
- const result = await executor.execute(createExampleInvocation(), [])
+ const result = executor.execute(createExampleInvocation(), [])
expect(result).not.toBeNull()
expect(result!.error).toEqual('Division by zero')
@@ -100,25 +96,29 @@ describe('RustVmExecutor', () => {
['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 })])
+ ])('falls back to the node vm on %s', (_name, error) => {
+ mockHogvmNode.executeSync.mockReturnValue(rustResult({ result: undefined, error }))
- await expect(executor.execute(createExampleInvocation(), [])).resolves.toBeNull()
+ expect(executor.execute(createExampleInvocation(), [])).toBeNull()
})
- it('falls back to the node vm when the ffi boundary throws instead of returning an error', async () => {
+ it('falls back to the node vm when the ffi boundary throws instead of returning an error', () => {
// e.g. globals containing NaN/Infinity, which serde_json can't represent.
- mockHogvmNode.executeBatch.mockRejectedValue(new Error('Failed to convert js number to serde_json::Number'))
+ mockHogvmNode.executeSync.mockImplementation(() => {
+ throw new Error('Failed to convert js number to serde_json::Number')
+ })
- await expect(executor.execute(createExampleInvocation(), [])).resolves.toBeNull()
+ expect(executor.execute(createExampleInvocation(), [])).toBeNull()
})
- it('redacts sensitive values from fallback logs', async () => {
+ it('redacts sensitive values from fallback logs', () => {
// Marshalling errors and panic messages can embed values from the invocation globals.
const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {})
- mockHogvmNode.executeBatch.mockRejectedValue(new Error('failed to convert value "secret-token" at inputs'))
+ mockHogvmNode.executeSync.mockImplementation(() => {
+ throw new Error('failed to convert value "secret-token" at inputs')
+ })
- await expect(executor.execute(createExampleInvocation(), ['secret-token'])).resolves.toBeNull()
+ expect(executor.execute(createExampleInvocation(), ['secret-token'])).toBeNull()
const fallbackCalls = warnSpy.mock.calls.filter((call) => String(call[1]).includes('fell back'))
expect(fallbackCalls).toHaveLength(1)
@@ -126,12 +126,12 @@ describe('RustVmExecutor', () => {
expect(JSON.stringify(fallbackCalls)).toContain('***REDACTED***')
})
- it('falls back to the node vm when the native addon is unavailable', async () => {
+ it('falls back to the node vm when the native addon is unavailable', () => {
mockHogvmNode.init.mockImplementation(() => {
throw new Error('addon not built')
})
- await expect(executor.execute(createExampleInvocation(), [])).resolves.toBeNull()
- expect(mockHogvmNode.executeBatch).not.toHaveBeenCalled()
+ expect(executor.execute(createExampleInvocation(), [])).toBeNull()
+ expect(mockHogvmNode.executeSync).not.toHaveBeenCalled()
})
})
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
index 27aa05052b21..2faad4606c1f 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
@@ -40,7 +40,7 @@ export class RustVmExecutor {
* null for the caller to pass through.
*/
private fallback(
- outcome: 'fallback_unsupported' | 'fallback_exception' | 'fallback_empty_result',
+ outcome: 'fallback_unsupported' | 'fallback_exception',
invocation: CyclotronJobInvocationHogFunction,
sensitiveValues: string[],
error: unknown
@@ -61,16 +61,15 @@ export class RustVmExecutor {
* 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.
+ * Runs through `executeSync` on the JS thread — the same threading model as the Node VM's
+ * exec, minus the work. Executions are sub-millisecond and bounded by the step budget, so a
+ * libuv thread-hop per invocation would cost more than the execution it offloads; batching
+ * many events into one async call is the follow-up if that changes.
*/
- public async execute(
+ public execute(
invocation: CyclotronJobInvocationHogFunction,
sensitiveValues: string[]
- ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null> {
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null {
const module_ = this.getModule()
if (!module_) {
// No per-invocation log: a missing addon affects every invocation and the loader
@@ -81,7 +80,7 @@ export class RustVmExecutor {
let rust
try {
- ;[rust] = await module_.executeBatch(invocation.hogFunction.bytecode, [invocation.state.globals], {
+ rust = module_.executeSync(invocation.hogFunction.bytecode, invocation.state.globals, {
maxSteps: RUST_MAX_STEPS,
})
} catch (error) {
@@ -93,9 +92,6 @@ export class RustVmExecutor {
// rather than being silently healed.
return this.fallback('fallback_exception', invocation, sensitiveValues, error)
}
- if (!rust) {
- return this.fallback('fallback_empty_result', invocation, sensitiveValues, undefined)
- }
if (rust.error && isUnsupportedByRustVm(rust.error)) {
return this.fallback('fallback_unsupported', invocation, sensitiveValues, rust.error)
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
deleted file mode 100644
index 1f6d98a1dc1b..000000000000
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import { init } from '@posthog/hogvm-node'
-
-import {
- RustVmShadow,
- ShadowNodeResult,
- ShadowOutcome,
- classifyShadowOutcome,
- shadowComparison,
-} from './rust-vm-shadow'
-
-jest.mock('@posthog/hogvm-node', () => ({
- init: jest.fn(),
- executeBatch: jest.fn(),
-}))
-
-const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
-
-const finishedNode = (execResult: unknown): ShadowNodeResult => ({
- finished: true,
- execResultJson: execResult !== undefined ? JSON.stringify(execResult) : null,
- durationMs: 1,
-})
-
-const capture = (functionId: string, globals: Record<string, unknown>, execResult: unknown) => ({
- functionId,
- teamId: 1,
- bytecode: ['_H', 1, 38],
- globalsJson: JSON.stringify(globals),
- node: finishedNode(execResult),
-})
-
-async function outcomeCounts(): Promise<Record<string, number>> {
- const data = await shadowComparison.get()
- return Object.fromEntries(data.values.map((v) => [v.labels.outcome, v.value]))
-}
-
-describe('RustVmShadow', () => {
- beforeEach(() => {
- jest.clearAllMocks()
- shadowComparison.reset()
- })
-
- describe('classifyShadowOutcome', () => {
- it.each<
- [
- string,
- ShadowNodeResult,
- { result?: unknown; error?: string; durationUs: number } | undefined,
- ShadowOutcome,
- ]
- >([
- [
- 'equal results',
- finishedNode({ a: [1, { b: 2 }] }),
- { result: { a: [1, { b: 2 }] }, durationUs: 1 },
- 'match',
- ],
- ['differing results', finishedNode({ a: 1 }), { result: { a: 2 }, durationUs: 1 }, 'result_mismatch'],
- ['node null result vs rust null', finishedNode(undefined), { result: null, durationUs: 1 }, 'match'],
- [
- 'node finished but rust errored',
- finishedNode({}),
- { error: 'Division by zero', durationUs: 1 },
- 'status_mismatch',
- ],
- [
- 'both errored',
- { finished: false, error: 'boom', execResultJson: null, durationMs: 1 },
- { error: 'Division by zero', durationUs: 1 },
- 'match',
- ],
- [
- 'node errored but rust finished',
- { finished: false, error: 'boom', execResultJson: null, durationMs: 1 },
- { result: 1, durationUs: 1 },
- 'status_mismatch',
- ],
- [
- 'unsupported host function',
- finishedNode({}),
- { error: 'Native call failed: unsupported_ext_fn:geoipLookup', durationUs: 1 },
- 'skipped_unsupported',
- ],
- [
- 'host function missing from the rust vm',
- finishedNode({}),
- { error: 'Unknown function sendEmail', durationUs: 1 },
- 'skipped_unsupported',
- ],
- ['missing rust result', finishedNode({}), undefined, 'rust_error'],
- ])('%s', (_name, node, rust, expected) => {
- expect(classifyShadowOutcome(node, rust)).toEqual(expected)
- })
- })
-
- describe('flush', () => {
- let shadow: RustVmShadow
-
- beforeEach(() => {
- shadow = new RustVmShadow({ sampleRate: 1, mmdbPath: '/dev/null' })
- })
-
- it('executes one rust batch per function with the captured pre-execution globals, pairing results by index', async () => {
- shadow.capture(capture('fn-a', { name: 'a1' }, 'ok-a1'))
- shadow.capture(capture('fn-b', { name: 'b1' }, 'ok-b1'))
- shadow.capture(capture('fn-a', { name: 'a2' }, 'ok-a2'))
-
- mockHogvmNode.executeBatch.mockImplementation((_program, events) =>
- Promise.resolve(
- (events as { name: string }[]).map((event) => ({
- // fn-a's second invocation diverges, everything else matches
- result: event.name === 'a2' ? 'rust-divergence' : `ok-${event.name}`,
- durationUs: 5,
- }))
- )
- )
-
- await shadow.flush()
-
- expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(2)
- expect(mockHogvmNode.executeBatch.mock.calls[0][1]).toEqual([{ name: 'a1' }, { name: 'a2' }])
- expect(mockHogvmNode.executeBatch.mock.calls[1][1]).toEqual([{ name: 'b1' }])
- expect(await outcomeCounts()).toEqual({ match: 2, result_mismatch: 1 })
- })
-
- it('a failing rust batch resolves the flush, counts rust_error, and does not affect other groups', async () => {
- shadow.capture(capture('fn-a', { name: 'a1' }, 'ok-a1'))
- shadow.capture(capture('fn-b', { name: 'b1' }, 'ok-b1'))
-
- mockHogvmNode.executeBatch
- .mockRejectedValueOnce(new Error('napi exploded'))
- .mockResolvedValueOnce([{ result: 'ok-b1', durationUs: 5 }])
-
- await expect(shadow.flush()).resolves.toBeUndefined()
- expect(await outcomeCounts()).toEqual({ rust_error: 1, match: 1 })
- })
-
- it('mutating the node result object after capture does not affect the comparison', async () => {
- // The transformer appends bookkeeping properties to the live execResult object right
- // after execution; the capture must compare against a point-in-time snapshot.
- const execResult: Record<string, unknown> = { properties: { $ip: '1.2.3.0' } }
- shadow.capture(capture('fn-a', { name: 'a1' }, execResult))
- ;(execResult.properties as Record<string, unknown>).$transformations_succeeded = ['fn-a']
-
- mockHogvmNode.executeBatch.mockResolvedValue([
- { result: { properties: { $ip: '1.2.3.0' } }, durationUs: 5 },
- ])
-
- await shadow.flush()
- expect(await outcomeCounts()).toEqual({ match: 1 })
- })
-
- it('a flush while a native batch is still running drops its captures instead of stacking', async () => {
- let resolveBatch: (results: unknown[]) => void = () => {}
- mockHogvmNode.executeBatch.mockImplementationOnce(
- () => new Promise((resolve) => (resolveBatch = resolve as (results: unknown[]) => void))
- )
-
- shadow.capture(capture('fn-a', { name: 'a1' }, 'ok-a1'))
- const firstFlush = shadow.flush()
-
- shadow.capture(capture('fn-a', { name: 'a2' }, 'ok-a2'))
- await shadow.flush()
-
- expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
- expect(await outcomeCounts()).toEqual({ dropped: 1 })
-
- resolveBatch([{ result: 'ok-a1', durationUs: 5 }])
- await firstFlush
- expect(await outcomeCounts()).toEqual({ dropped: 1, match: 1 })
- })
-
- it('functions calling nondeterministic stl fns are skipped at capture, not compared', async () => {
- // CALL_GLOBAL randomFloat — two executions legitimately differ, comparison is meaningless.
- shadow.capture({ ...capture('fn-rng', { name: 'a' }, 'ok'), bytecode: ['_H', 1, 2, 'randomFloat', 0, 38] })
- // A string literal containing a fn name (preceded by the STRING op 32) must not skip.
- shadow.capture({ ...capture('fn-str', { name: 'b' }, 'now'), bytecode: ['_H', 1, 32, 'now', 38] })
-
- mockHogvmNode.executeBatch.mockResolvedValue([{ result: 'now', durationUs: 5 }])
- await shadow.flush()
-
- expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
- expect(await outcomeCounts()).toEqual({ skipped_nondeterministic: 1, match: 1 })
- })
-
- it('captures beyond the buffer cap are counted as dropped, not as rust errors', async () => {
- for (let i = 0; i < 10_001; i++) {
- shadow.capture(capture('fn-a', { name: 'a' }, 'ok'))
- }
- expect(await outcomeCounts()).toEqual({ dropped: 1 })
- })
-
- it('flush drains the buffer, so a second flush does nothing', async () => {
- shadow.capture(capture('fn-a', { name: 'a1' }, 'ok-a1'))
- mockHogvmNode.executeBatch.mockResolvedValue([{ result: 'ok-a1', durationUs: 5 }])
-
- await shadow.flush()
- await shadow.flush()
-
- expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
- })
- })
-
- it('a zero sample rate never captures nor loads the native module', () => {
- const shadow = new RustVmShadow({ sampleRate: 0, mmdbPath: '/dev/null' })
- expect(shadow.shouldCapture()).toEqual(false)
- expect(init).not.toHaveBeenCalled()
- })
-})
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
deleted file mode 100644
index dbc1641c7840..000000000000
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import deepEqual from 'fast-deep-equal'
-import { Counter, Histogram } from 'prom-client'
-
-import { HogBytecode } from '~/cdp/types'
-import { parseJSON } from '~/common/utils/json-parse'
-import { logger } from '~/common/utils/logger'
-
-import { HogvmNodeModule, RUST_MAX_STEPS, RustExecResult, isUnsupportedByRustVm, loadHogvmNodeModule } from './rust-vm'
-
-/**
- * Shadow-executes sampled transformation invocations on the Rust HogVM (via the
- * `@posthog/hogvm-node` napi addon) to compare latency and correctness against the Node VM. The
- * Node result stays authoritative: captures buffer in memory and execute per batch during the
- * transformer's flush, results are discarded after comparison, and any failure only surfaces as a
- * metric or log.
- *
- * The native addon is optional — if it isn't built for this environment the shadow disables
- * itself.
- */
-
-// 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'])
-const CALL_GLOBAL_OP = 2
-// Safety cap so a stalled flush can't grow the buffer unboundedly.
-const MAX_BUFFER_SIZE = 10_000
-
-export const shadowExecutionDuration = new Histogram({
- name: 'hogvm_shadow_execution_duration_ms',
- help: 'Per-invocation hog execution duration for shadow-sampled transformations, by VM',
- labelNames: ['vm'],
- buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 100],
-})
-
-export const shadowBatchDuration = new Histogram({
- name: 'hogvm_shadow_batch_duration_ms',
- help: 'Wall time of one rust executeBatch napi call, marshalling included',
- buckets: [0.5, 1, 2.5, 5, 10, 25, 50, 100, 250, 500],
-})
-
-export const shadowFlushSize = new Histogram({
- name: 'hogvm_shadow_flush_invocations',
- help: 'Captured invocations per shadow flush (scope=flush) and per function group within it (scope=function) — group size is what the rayon fan-out sees',
- labelNames: ['scope'],
- buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
-})
-
-export const shadowComparison = new Counter({
- name: 'hogvm_shadow_comparison_total',
- help: 'Outcomes of node-vs-rust hogvm shadow comparisons',
- labelNames: ['outcome'],
-})
-
-export type ShadowOutcome =
- | 'match'
- | 'result_mismatch'
- | 'status_mismatch'
- | 'rust_error'
- | 'skipped_unsupported'
- | 'skipped_nondeterministic'
- | 'dropped'
-
-export interface ShadowNodeResult {
- finished: boolean
- error?: string
- /** JSON snapshot of execResult taken at capture time — the transformer mutates the live
- * object right after execution (bookkeeping properties, chained transformations). */
- execResultJson: string | null
- durationMs: number
-}
-
-export interface ShadowCapturedInvocation {
- functionId: string
- teamId: number
- bytecode: HogBytecode
- /** state.globals snapshot taken before the Node VM ran (later transformations mutate them). */
- globalsJson: string
- node: ShadowNodeResult
-}
-
-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.
- if (isUnsupportedByRustVm(rust.error)) {
- return 'skipped_unsupported'
- }
- // Both VMs failed the program: they agree.
- return !node.finished || node.error ? 'match' : 'status_mismatch'
- }
- if (!node.finished || node.error) {
- return 'status_mismatch'
- }
- const nodeResult = node.execResultJson != null ? parseJSON(node.execResultJson) : null
- return deepEqual(nodeResult, rust.result ?? null) ? 'match' : 'result_mismatch'
-}
-
-export class RustVmShadow {
- private buffer: ShadowCapturedInvocation[] = []
- private module_: HogvmNodeModule | null | undefined = undefined
- private flushInFlight = false
- private nondeterministicByFunction = new Map<string, boolean>()
-
- constructor(
- private options: {
- sampleRate: number
- mmdbPath: string
- }
- ) {}
-
- /** True for the sampled fraction of invocations, and only when the native addon is loadable. */
- public shouldCapture(): boolean {
- if (this.options.sampleRate <= 0 || !this.getModule()) {
- return false
- }
- return Math.random() < this.options.sampleRate
- }
-
- public capture(item: ShadowCapturedInvocation): void {
- if (this.isNondeterministic(item.functionId, item.bytecode)) {
- shadowComparison.inc({ outcome: 'skipped_nondeterministic' })
- return
- }
- if (this.buffer.length >= MAX_BUFFER_SIZE) {
- shadowComparison.inc({ outcome: 'dropped' })
- return
- }
- this.buffer.push(item)
- }
-
- // Every string literal in hog bytecode is preceded by the STRING op (32); only CALL_GLOBAL (2)
- // is directly followed by the function name, so this pair scan cannot false-positive on string
- // literals that merely contain a function name.
- private isNondeterministic(functionId: string, bytecode: HogBytecode): boolean {
- let cached = this.nondeterministicByFunction.get(functionId)
- if (cached === undefined) {
- cached = bytecode.some(
- (token, index) =>
- token === CALL_GLOBAL_OP &&
- typeof bytecode[index + 1] === 'string' &&
- NONDETERMINISTIC_FNS.has(bytecode[index + 1] as string)
- )
- if (this.nondeterministicByFunction.size >= MAX_BUFFER_SIZE) {
- this.nondeterministicByFunction.clear()
- }
- this.nondeterministicByFunction.set(functionId, cached)
- }
- return cached
- }
-
- /**
- * Execute everything captured since the last flush on the Rust VM and compare. Runs off the
- * hot path (the transformer's afterBatch drain); callers wrap it in `mirrorCall` so it can
- * never affect the primary pipeline.
- */
- public async flush(): Promise<void> {
- const items = this.buffer
- this.buffer = []
- const module_ = this.getModule()
- if (!module_ || items.length === 0) {
- return
- }
-
- // The caller's mirrorCall timeout only stops awaiting — the native batch keeps running on
- // its worker threads. Never stack batches: while one is in flight, drop new captures.
- if (this.flushInFlight) {
- shadowComparison.inc({ outcome: 'dropped' }, items.length)
- return
- }
- this.flushInFlight = true
-
- shadowFlushSize.observe({ scope: 'flush' }, items.length)
-
- try {
- await this.executeAndCompare(items)
- } finally {
- this.flushInFlight = false
- }
- }
-
- private async executeAndCompare(items: ShadowCapturedInvocation[]): Promise<void> {
- const module_ = this.getModule()
- if (!module_) {
- return
- }
-
- const byFunction = new Map<string, ShadowCapturedInvocation[]>()
- for (const item of items) {
- const group = byFunction.get(item.functionId)
- if (group) {
- group.push(item)
- } else {
- byFunction.set(item.functionId, [item])
- }
- }
-
- for (const group of byFunction.values()) {
- shadowFlushSize.observe({ scope: 'function' }, group.length)
- let rustResults: RustExecResult[] = []
- const stopTimer = shadowBatchDuration.startTimer()
- try {
- rustResults = await module_.executeBatch(
- group[0].bytecode,
- group.map((item) => parseJSON(item.globalsJson)),
- { parallel: true, maxSteps: RUST_MAX_STEPS }
- )
- } catch (error) {
- logger.warn('🦀', 'Rust HogVM shadow batch failed', {
- functionId: group[0].functionId,
- error: String(error),
- })
- } finally {
- stopTimer()
- }
-
- let mismatchLogged = false
- group.forEach((item, index) => {
- const rust: RustExecResult | undefined = rustResults[index]
- shadowExecutionDuration.observe({ vm: 'node' }, item.node.durationMs)
- if (rust) {
- shadowExecutionDuration.observe({ vm: 'rust' }, rust.durationUs / 1000)
- }
- const outcome = classifyShadowOutcome(item.node, rust)
- shadowComparison.inc({ outcome })
- // One example per function per flush is enough to identify a diverging function
- // without flooding the logs; replay its bytecode offline for the actual diff.
- if ((outcome === 'result_mismatch' || outcome === 'status_mismatch') && !mismatchLogged) {
- mismatchLogged = true
- logger.warn('🦀', 'Rust HogVM shadow divergence', {
- outcome,
- functionId: item.functionId,
- teamId: item.teamId,
- nodeError: item.node.error,
- rustError: rust?.error,
- })
- }
- })
- }
- }
-
- private getModule(): HogvmNodeModule | null {
- if (this.module_ !== undefined) {
- return this.module_
- }
- if (this.options.sampleRate <= 0) {
- this.module_ = null
- return null
- }
- this.module_ = loadHogvmNodeModule({ mmdbPath: this.options.mmdbPath })
- if (this.module_) {
- logger.info('🦀', 'Rust HogVM shadow mode enabled', { sampleRate: this.options.sampleRate })
- }
- return this.module_
- }
-}
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm.ts b/nodejs/src/cdp/hog-transformations/rust-vm.ts
index 3deb06eab314..c4b75a79a372 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm.ts
@@ -24,9 +24,8 @@ 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.
+ * uses this to hand the invocation to the Node VM. Real execution errors must never match — the
+ * caller would otherwise run the program twice.
*/
export function isUnsupportedByRustVm(error: string): boolean {
return (
@@ -48,11 +47,6 @@ export interface RustExecResult {
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
}
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 82144cb7a065..2722b462bafe 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -187,10 +187,6 @@ export type CommonConfig = BaseServerConfig & {
// Shared between ingestion and CDP (used by hog transformer in both)
CDP_HOG_WATCHER_SAMPLE_RATE: number
- // Fraction (0-1) of transformation executions shadow-executed on the Rust HogVM for
- // 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
@@ -365,7 +361,6 @@ 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
diff --git a/rust/common/hogvm/node/Cargo.lock b/rust/common/hogvm/node/Cargo.lock
index bfc9eda97c87..c31e0861aae3 100644
--- a/rust/common/hogvm/node/Cargo.lock
+++ b/rust/common/hogvm/node/Cargo.lock
@@ -130,31 +130,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "crossbeam-deque"
-version = "0.8.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
-dependencies = [
- "crossbeam-epoch",
- "crossbeam-utils",
-]
-
-[[package]]
-name = "crossbeam-epoch"
-version = "0.9.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
-dependencies = [
- "crossbeam-utils",
-]
-
-[[package]]
-name = "crossbeam-utils"
-version = "0.8.21"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
-
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -186,12 +161,6 @@ dependencies = [
"subtle",
]
-[[package]]
-name = "either"
-version = "1.16.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
-
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -311,7 +280,6 @@ dependencies = [
"napi",
"napi-build",
"napi-derive",
- "rayon",
"serde_json",
]
@@ -630,26 +598,6 @@ dependencies = [
"getrandom 0.2.17",
]
-[[package]]
-name = "rayon"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
-dependencies = [
- "either",
- "rayon-core",
-]
-
-[[package]]
-name = "rayon-core"
-version = "1.13.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
-dependencies = [
- "crossbeam-deque",
- "crossbeam-utils",
-]
-
[[package]]
name = "redox_syscall"
version = "0.5.18"
diff --git a/rust/common/hogvm/node/Cargo.toml b/rust/common/hogvm/node/Cargo.toml
index cb501de8ed23..ead9fe1ce5a0 100644
--- a/rust/common/hogvm/node/Cargo.toml
+++ b/rust/common/hogvm/node/Cargo.toml
@@ -21,7 +21,6 @@ hogvm = { path = ".." }
maxminddb = "0.24"
napi = { version = "2", default-features = false, features = ["napi8", "serde-json"] }
napi-derive = "2"
-rayon = "1.10"
serde_json = "1.0"
[build-dependencies]
diff --git a/rust/common/hogvm/node/index.d.ts b/rust/common/hogvm/node/index.d.ts
index 00fc07386868..0aabc8d7150d 100644
--- a/rust/common/hogvm/node/index.d.ts
+++ b/rust/common/hogvm/node/index.d.ts
@@ -18,13 +18,6 @@ export interface HogExecResult {
logsTruncated?: boolean
}
-export interface ExecuteBatchOptions {
- /** Fan the batch out over a rayon thread pool instead of running sequentially. */
- parallel?: boolean
- /** Step budget per execution (the Rust VM has no wall-clock timeout). */
- maxSteps?: number
-}
-
export interface ExecuteSyncOptions {
/** Step budget for the execution (the Rust VM has no wall-clock timeout). */
maxSteps?: number
@@ -36,16 +29,6 @@ export interface ExecuteSyncOptions {
*/
export function init(options: InitOptions): void
-/**
- * Run one Hog program (bytecode tokens) against many event-globals, off the JS event loop.
- * Returns one structured result per event, in input order.
- */
-export function executeBatch(
- program: unknown[],
- 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
diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rs
index 24d0c96c849b..74551dd1164a 100644
--- a/rust/common/hogvm/node/src/exec.rs
+++ b/rust/common/hogvm/node/src/exec.rs
@@ -4,16 +4,13 @@ use std::time::Instant;
use hogvm::{sync_execute, ExecutionContext, Program};
use napi_derive::napi;
-use rayon::prelude::*;
use serde_json::Value;
use crate::ext_fns::transformation_ext_fns;
use crate::logs;
-const PARALLEL_CHUNK_SIZE: usize = 500;
-
// The Node VM has no heap ceiling; the crate's 1MB default trips on real events with large
-// properties. A cap (not a preallocation), and rayon bounds how many contexts run at once.
+// properties. A cap, not a preallocation.
const MAX_HEAP_SIZE_BYTES: usize = 64 * 1024 * 1024;
#[napi(object)]
@@ -31,7 +28,6 @@ pub struct HogExecResult {
pub fn run_batch(
tokens: &[Value],
events: &[Value],
- parallel: bool,
max_steps: Option<usize>,
) -> Vec<HogExecResult> {
if tokens.is_empty() {
@@ -41,18 +37,11 @@ pub fn run_batch(
.collect();
}
- if !parallel {
- return run_chunk(tokens, events, max_steps);
- }
-
- events
- .par_chunks(PARALLEL_CHUNK_SIZE)
- .flat_map_iter(|chunk| run_chunk(tokens, chunk, max_steps).into_iter())
- .collect()
+ run_chunk(tokens, events, max_steps)
}
-// Run a slice of events through one reused ExecutionContext (STL and ext fns built once, globals
-// swapped per event).
+// Run the events through one reused ExecutionContext (STL and ext fns built once, globals
+// swapped per event), sequentially on the calling thread.
fn run_chunk(tokens: &[Value], chunk: &[Value], max_steps: Option<usize>) -> Vec<HogExecResult> {
let program = match Program::new(tokens.to_vec()) {
Ok(p) => p,
@@ -166,21 +155,19 @@ mod tests {
let events: Vec<Value> = (0..1200)
.map(|i| json!({ "name": i.to_string() }))
.collect();
- for parallel in [false, true] {
- let results = run_batch(&get_global_program("name"), &events, parallel, None);
- assert_eq!(results.len(), events.len());
- for (i, r) in results.iter().enumerate() {
- assert_eq!(r.error, None);
- assert_eq!(r.result, Some(json!(i.to_string())));
- assert!(r.duration_us > 0.0);
- }
+ let results = run_batch(&get_global_program("name"), &events, None);
+ assert_eq!(results.len(), events.len());
+ for (i, r) in results.iter().enumerate() {
+ assert_eq!(r.error, None);
+ assert_eq!(r.result, Some(json!(i.to_string())));
+ assert!(r.duration_us > 0.0);
}
}
#[test]
fn per_event_error_does_not_fail_the_batch() {
let events = vec![json!({ "name": "ok" }), json!({ "other": 1 })];
- let results = run_batch(&get_global_program("name"), &events, false, None);
+ let results = run_batch(&get_global_program("name"), &events, None);
assert_eq!(results[0].result, Some(json!("ok")));
assert!(results[1].result.is_none());
assert!(results[1].error.as_deref().unwrap().contains("name"));
@@ -188,12 +175,7 @@ mod tests {
#[test]
fn invalid_program_errors_every_event() {
- let results = run_batch(
- &[json!("not bytecode")],
- &[json!({}), json!({})],
- false,
- None,
- );
+ let results = run_batch(&[json!("not bytecode")], &[json!({}), json!({})], None);
assert_eq!(results.len(), 2);
for r in &results {
assert!(r.error.as_deref().unwrap().starts_with("invalid program"));
@@ -202,7 +184,7 @@ mod tests {
#[test]
fn empty_program_errors_every_event() {
- let results = run_batch(&[], &[json!({})], false, None);
+ let results = run_batch(&[], &[json!({})], None);
assert!(results[0].error.is_some());
}
@@ -218,7 +200,7 @@ mod tests {
json!(13),
json!(38),
];
- let results = run_batch(&gt_true_zero, &[json!({})], false, None);
+ let results = run_batch(&gt_true_zero, &[json!({})], None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].result, Some(json!(true)));
@@ -232,27 +214,22 @@ mod tests {
json!(15),
json!(38),
];
- let results = run_batch(&lt_zero_null, &[json!({})], false, None);
+ let results = run_batch(&lt_zero_null, &[json!({})], None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].result, Some(json!(false)));
}
#[test]
fn max_steps_budget_is_enforced() {
- let results = run_batch(&add_program(), &[json!({})], false, Some(1));
+ let results = run_batch(&add_program(), &[json!({})], Some(1));
assert!(results[0].error.is_some());
- let results = run_batch(&add_program(), &[json!({})], false, None);
+ let results = run_batch(&add_program(), &[json!({})], None);
assert_eq!(results[0].result, Some(json!(3)));
}
#[test]
fn posthog_capture_errors_like_the_node_executor() {
- let results = run_batch(
- &call_fn_program("postHogCapture", "x"),
- &[json!({})],
- false,
- None,
- );
+ let results = run_batch(&call_fn_program("postHogCapture", "x"), &[json!({})], None);
assert!(results[0]
.error
.as_deref()
@@ -265,7 +242,6 @@ mod tests {
let results = run_batch(
&call_fn_program("generateMessagingPreferencesUrl", "x"),
&[json!({})],
- false,
None,
);
assert!(results[0]
@@ -281,7 +257,6 @@ mod tests {
let results = run_batch(
&call_fn_program("geoipLookup", "89.160.20.129"),
&[json!({})],
- false,
None,
);
assert!(results[0]
@@ -299,7 +274,6 @@ mod tests {
let results = run_batch(
&call_fn_program("someFunctionNobodyImplements", "x"),
&[json!({})],
- false,
None,
);
assert!(results[0]
@@ -308,7 +282,7 @@ mod tests {
.unwrap()
.starts_with("Unknown function "));
- let results = run_batch(&get_global_program("missing"), &[json!({})], false, None);
+ let results = run_batch(&get_global_program("missing"), &[json!({})], None);
assert!(results[0]
.error
.as_deref()
@@ -330,7 +304,7 @@ mod tests {
json!(35),
];
program.extend(add_program().into_iter().skip(2));
- let results = run_batch(&program, &[json!({})], false, None);
+ let results = run_batch(&program, &[json!({})], None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].result, Some(json!(3)));
assert_eq!(results[0].logs, vec!["x".to_string()]);
@@ -353,44 +327,11 @@ mod tests {
json!(38),
];
let events = vec![json!({ "g": { "a": 1 } }), json!({ "g": "plain" })];
- let results = run_batch(&program, &events, false, None);
+ let results = run_batch(&program, &events, 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.
@@ -406,7 +347,7 @@ mod tests {
]);
}
program.extend(add_program().into_iter().skip(2));
- let results = run_batch(&program, &[json!({})], false, None);
+ let results = run_batch(&program, &[json!({})], None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].logs.len(), crate::logs::MAX_CAPTURED_LOGS);
assert!(results[0].logs_truncated);
@@ -414,7 +355,7 @@ mod tests {
// 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);
+ let results = run_batch(&add_program(), &[json!({})], None);
assert_eq!(results[0].logs, Vec::<String>::new());
assert!(!results[0].logs_truncated);
}
@@ -425,14 +366,12 @@ mod tests {
let results = run_batch(
&call_fn_program("isKnownBotUserAgent", "Mozilla/5.0 GoogleBot/2.1"),
&[json!({})],
- false,
None,
);
assert_eq!(results[0].result, Some(json!(true)));
let results = run_batch(
&call_fn_program("isKnownBotUserAgent", "Mozilla/5.0 Safari"),
&[json!({})],
- false,
None,
);
assert_eq!(results[0].result, Some(json!(false)));
@@ -444,14 +383,12 @@ mod tests {
let results = run_batch(
&call_fn_program("isKnownBotIp", "1.2.3.4"),
&[json!({})],
- false,
None,
);
assert_eq!(results[0].result, Some(json!(true)));
let results = run_batch(
&call_fn_program("isKnownBotIp", "1.2.3.40"),
&[json!({})],
- false,
None,
);
assert_eq!(results[0].result, Some(json!(false)));
@@ -462,7 +399,6 @@ mod tests {
let results = run_batch(
&call_fn_program("cleanNullValues", "unused"),
&[json!({})],
- false,
None,
);
// A string arg passes through untouched.
@@ -484,7 +420,6 @@ mod tests {
let results = run_batch(
&program,
&[json!({ "g": { "a": null, "b": 1, "c": [null, 2] } })],
- false,
None,
);
assert_eq!(results[0].result, Some(json!({ "b": 1, "c": [2] })));
diff --git a/rust/common/hogvm/node/src/lib.rs b/rust/common/hogvm/node/src/lib.rs
index 469968345aff..af214c4ad787 100644
--- a/rust/common/hogvm/node/src/lib.rs
+++ b/rust/common/hogvm/node/src/lib.rs
@@ -1,27 +1,22 @@
//! Rust HogVM exposed to Node via napi-rs, for executing ingestion transformations.
//!
-//! 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.
+//! `executeSync` runs one (bytecode, globals) pair synchronously on the calling thread — the
+//! primary-execution path, matching the Node VM's synchronous exec with no threadpool round-trip.
+//! Executions are sub-millisecond and bounded by the step budget, so blocking the event loop is
+//! no worse than the Node VM path it replaces.
//!
//! Transformation host functions (`geoipLookup`, `cleanNullValues`, `isKnownBotUserAgent`,
//! `isKnownBotIp`) mirror `nodejs/src/cdp/hog-transformations/transformation-functions.ts`; call
//! `init` once with the mmdb path and bot lists before executing. A host function this binding
//! can't support fails the execution with an `unsupported_ext_fn:<name>` error so the caller can
-//! classify it as skipped rather than as a mismatch.
+//! fall back to the Node VM.
mod exec;
mod ext_fns;
mod geoip;
mod logs;
-#[cfg(not(feature = "noop"))]
-use napi::bindgen_prelude::AsyncTask;
use napi::Result as NapiResult;
-#[cfg(not(feature = "noop"))]
-use napi::{Env, Task};
use napi_derive::napi;
use serde_json::Value;
@@ -45,65 +40,6 @@ pub fn init(options: InitOptions) -> NapiResult<()> {
Ok(())
}
-#[napi(object)]
-pub struct ExecuteBatchOptions {
- /// Fan the batch out over a rayon thread pool instead of running sequentially.
- pub parallel: Option<bool>,
- /// Step budget per execution (the Rust VM has no wall-clock timeout).
- pub max_steps: Option<u32>,
-}
-
-#[cfg(not(feature = "noop"))]
-pub struct ExecuteBatchTask {
- tokens: Vec<Value>,
- events: Vec<Value>,
- parallel: bool,
- max_steps: Option<usize>,
-}
-
-// The `noop` test build strips the generated ToNapiValue impls the Task bound needs; tests
-// exercise `run_batch` directly.
-#[cfg(not(feature = "noop"))]
-impl Task for ExecuteBatchTask {
- type Output = Vec<HogExecResult>;
- type JsValue = Vec<HogExecResult>;
-
- fn compute(&mut self) -> NapiResult<Self::Output> {
- let tokens = std::mem::take(&mut self.tokens);
- let events = std::mem::take(&mut self.events);
- Ok(run_batch(&tokens, &events, self.parallel, self.max_steps))
- }
-
- fn resolve(&mut self, _env: Env, output: Self::Output) -> NapiResult<Self::JsValue> {
- Ok(output)
- }
-}
-
-/// Run one Hog program (bytecode tokens) against many event-globals, off the JS event loop.
-/// Returns one structured result per event, in input order.
-#[cfg(not(feature = "noop"))]
-#[napi(ts_return_type = "Promise<Array<HogExecResult>>")]
-pub fn execute_batch(
- program: Value,
- events: Vec<Value>,
- options: Option<ExecuteBatchOptions>,
-) -> AsyncTask<ExecuteBatchTask> {
- let options = options.unwrap_or(ExecuteBatchOptions {
- parallel: None,
- max_steps: None,
- });
- let tokens = match program {
- Value::Array(tokens) => tokens,
- _ => Vec::new(),
- };
- AsyncTask::new(ExecuteBatchTask {
- tokens,
- events,
- parallel: options.parallel.unwrap_or(false),
- 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).
@@ -124,7 +60,7 @@ pub fn execute_sync(
_ => 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)
+ run_batch(&tokens, std::slice::from_ref(&globals), 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
index 872435681f51..7ff2e357dc62 100644
--- a/rust/common/hogvm/node/src/logs.rs
+++ b/rust/common/hogvm/node/src/logs.rs
@@ -1,9 +1,9 @@
//! 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.
+//! it writes to a thread-local buffer instead. An event executes entirely on the calling thread,
+//! so resetting the buffer before each execution and draining it right after cannot mix events
+//! up.
use std::cell::RefCell;