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): batch rust hogvm transformation execution behind a flag (#74536)

José Sequeiraffc03ea3acfb
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 cb55a8c53f35..4c8fac438fc4 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -24,6 +24,7 @@ import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
jest.mock('@posthog/hogvm-node', () => ({
init: jest.fn(),
executeSync: jest.fn(),
+ executeBatch: jest.fn(),
}))
const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
@@ -74,6 +75,7 @@ describe('HogTransformer', () => {
const config: HogTransformerServiceConfig = {
SITE_URL: hub.SITE_URL,
CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
+ CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED: false,
MMDB_FILE_LOCATION: hub.MMDB_FILE_LOCATION,
// Deliberately not the default, so the assertion below proves the value is plumbed
// through rather than hardcoded in the factory.
@@ -1591,5 +1593,28 @@ describe('HogTransformer', () => {
$current_url: 'https://example.com',
})
})
+
+ it('routes through executeBatch instead of executeSync when batch execution is enabled', async () => {
+ hub.CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED = true
+ hogTransformer = createHogTransformerService(hub, {
+ ...hub,
+ monitoringOutputs: createTestMonitoringOutputs(mockProducer),
+ })
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ {
+ result: { properties: { from_rust_batch: true } },
+ durationUs: 100,
+ logs: [],
+ logsTruncated: false,
+ },
+ ])
+
+ const result = await hogTransformer.transformEventAndProduceMessages(createPluginEvent({}, teamId))
+
+ expect(mockHogvmNode.executeSync).not.toHaveBeenCalled()
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeBatch.mock.calls[0][0]).toEqual(bytecode)
+ expect(result.event?.properties).toEqual({ from_rust_batch: true })
+ })
})
})
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index 686c4d33bc20..1182e6349e96 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -27,6 +27,7 @@ import { getTransformationFunctions } from './transformation-functions'
export interface HogTransformerConfig {
siteUrl: string
hogRustVmExecutionEnabled: boolean
+ hogRustVmBatchExecutionEnabled: boolean
mmdbFileLocation: string
}
@@ -331,7 +332,9 @@ export class HogTransformerService implements HogTransformer {
if (this.rustVmExecutor) {
const sensitiveValues = this.hogExecutor.getSensitiveValues(hogFunction, globalsWithInputs.inputs)
- const rustResult = this.rustVmExecutor.execute(invocation, sensitiveValues)
+ const rustResult = this.config.hogRustVmBatchExecutionEnabled
+ ? await this.rustVmExecutor.executeBatched(invocation, sensitiveValues)
+ : 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) {
@@ -346,7 +349,11 @@ export class HogTransformerService implements HogTransformer {
/** Config read by createHogTransformerService when running inside ingestion. */
export type HogTransformerServiceConfig = Pick<
CommonConfig,
- 'SITE_URL' | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED' | 'MMDB_FILE_LOCATION' | 'TRANSFORMATIONS_HOG_TIMEOUT_MS'
+ | 'SITE_URL'
+ | 'CDP_HOG_RUST_VM_EXECUTION_ENABLED'
+ | 'CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED'
+ | 'MMDB_FILE_LOCATION'
+ | 'TRANSFORMATIONS_HOG_TIMEOUT_MS'
>
export interface HogTransformerServiceDeps {
@@ -384,6 +391,7 @@ export function createHogTransformerService(
{
siteUrl: config.SITE_URL,
hogRustVmExecutionEnabled: config.CDP_HOG_RUST_VM_EXECUTION_ENABLED,
+ hogRustVmBatchExecutionEnabled: config.CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED,
mmdbFileLocation: config.MMDB_FILE_LOCATION,
}
)
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.test.ts
new file mode 100644
index 000000000000..e4b84f997f4f
--- /dev/null
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.test.ts
@@ -0,0 +1,102 @@
+import { RustExecResult } from './rust-vm'
+import { RustVmBatchScheduler } from './rust-vm-batch-scheduler'
+
+const execResult = (overrides: Partial<RustExecResult> = {}): RustExecResult => ({
+ result: 'ok',
+ durationUs: 100,
+ logs: [],
+ logsTruncated: false,
+ ...overrides,
+})
+
+describe('RustVmBatchScheduler', () => {
+ let runBatch: jest.Mock
+
+ beforeEach(() => {
+ runBatch = jest.fn((_program: unknown[], events: unknown[]) =>
+ Promise.resolve(events.map((_, index) => execResult({ result: `result-${index}` })))
+ )
+ })
+
+ it('coalesces same-program executions from one tick into a single call, mapping results back in order', async () => {
+ const scheduler = new RustVmBatchScheduler(runBatch)
+ const bytecode = ['_H', 1, 38]
+
+ const results = await Promise.all([
+ scheduler.execute(bytecode, { event: 'a' }),
+ scheduler.execute(bytecode, { event: 'b' }),
+ scheduler.execute(bytecode, { event: 'c' }),
+ ])
+
+ expect(runBatch).toHaveBeenCalledTimes(1)
+ expect(runBatch).toHaveBeenCalledWith(bytecode, [{ event: 'a' }, { event: 'b' }, { event: 'c' }])
+ expect(results.map((r) => r.result)).toEqual(['result-0', 'result-1', 'result-2'])
+ })
+
+ it('keeps different programs in separate batches', async () => {
+ const scheduler = new RustVmBatchScheduler(runBatch)
+ const programA = ['_H', 1, 38]
+ const programB = ['_H', 1, 35, 38]
+
+ await Promise.all([
+ scheduler.execute(programA, { event: 'a' }),
+ scheduler.execute(programB, { event: 'b' }),
+ scheduler.execute(programA, { event: 'c' }),
+ ])
+
+ expect(runBatch).toHaveBeenCalledTimes(2)
+ expect(runBatch).toHaveBeenCalledWith(programA, [{ event: 'a' }, { event: 'c' }])
+ expect(runBatch).toHaveBeenCalledWith(programB, [{ event: 'b' }])
+ })
+
+ it('dispatches a full queue immediately instead of letting it grow past the batch size cap', async () => {
+ const scheduler = new RustVmBatchScheduler(runBatch, 2)
+ const bytecode = ['_H', 1, 38]
+
+ await Promise.all([
+ scheduler.execute(bytecode, { event: 'a' }),
+ scheduler.execute(bytecode, { event: 'b' }),
+ scheduler.execute(bytecode, { event: 'c' }),
+ ])
+
+ expect(runBatch).toHaveBeenCalledTimes(2)
+ expect(runBatch).toHaveBeenCalledWith(bytecode, [{ event: 'a' }, { event: 'b' }])
+ expect(runBatch).toHaveBeenCalledWith(bytecode, [{ event: 'c' }])
+ })
+
+ it('executions enqueued after a flush go into the next batch', async () => {
+ const scheduler = new RustVmBatchScheduler(runBatch)
+ const bytecode = ['_H', 1, 38]
+
+ await scheduler.execute(bytecode, { event: 'a' })
+ await scheduler.execute(bytecode, { event: 'b' })
+
+ expect(runBatch).toHaveBeenCalledTimes(2)
+ })
+
+ it('a batch-level failure rejects every waiter in that batch, not just one', async () => {
+ runBatch.mockRejectedValue(new Error('addon exploded'))
+ const scheduler = new RustVmBatchScheduler(runBatch)
+ const bytecode = ['_H', 1, 38]
+
+ const outcomes = await Promise.allSettled([
+ scheduler.execute(bytecode, { event: 'a' }),
+ scheduler.execute(bytecode, { event: 'b' }),
+ ])
+
+ expect(outcomes.map((o) => o.status)).toEqual(['rejected', 'rejected'])
+ })
+
+ it('rejects all waiters when the batch returns the wrong number of results', async () => {
+ runBatch.mockResolvedValue([execResult()])
+ const scheduler = new RustVmBatchScheduler(runBatch)
+ const bytecode = ['_H', 1, 38]
+
+ const outcomes = await Promise.allSettled([
+ scheduler.execute(bytecode, { event: 'a' }),
+ scheduler.execute(bytecode, { event: 'b' }),
+ ])
+
+ expect(outcomes.map((o) => o.status)).toEqual(['rejected', 'rejected'])
+ })
+})
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts
new file mode 100644
index 000000000000..a2ea0bc08849
--- /dev/null
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts
@@ -0,0 +1,93 @@
+import { Histogram } from 'prom-client'
+
+import { RustExecResult } from './rust-vm'
+
+export const hogvmRustBatchFlushSize = new Histogram({
+ name: 'hogvm_rust_batch_flush_size',
+ help: 'Number of invocations of one hog program executed in a single executeBatch call',
+ buckets: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000],
+})
+
+export type RunBatchFn = (program: unknown[], events: unknown[]) => Promise<RustExecResult[]>
+
+interface QueueEntry {
+ globals: unknown
+ resolve: (result: RustExecResult) => void
+ reject: (error: unknown) => void
+}
+
+// Above this many queued invocations a program's queue is dispatched immediately instead of
+// waiting for the tick to end, bounding how much converted-event memory a single batch holds
+// and how long the first waiter sits in the queue. The Rust side derives its rayon chunk size
+// from the batch it receives, so this cap doesn't limit fan-out.
+export const DEFAULT_MAX_BATCH_SIZE = 500
+
+/**
+ * Coalesces individual transformation executions into per-program `executeBatch` calls.
+ *
+ * Callers `execute(bytecode, globals)` and await their own result; invocations that arrive within
+ * the same event-loop tick for the same program (keyed by bytecode reference — stable while the
+ * hog function manager caches the function, and a new version's new array simply starts its own
+ * batch) are flushed together on the next `setImmediate` as one FFI crossing, executed off the JS
+ * thread. Batch sizes therefore track how many events are concurrently at the transform step.
+ *
+ * A batch-level failure rejects every waiter in that batch — the caller decides what a rejection
+ * means (the executor treats it like a boundary throw and falls back to the Node VM).
+ */
+export class RustVmBatchScheduler {
+ private queues = new Map<unknown[], QueueEntry[]>()
+ private flushScheduled = false
+
+ constructor(
+ private runBatch: RunBatchFn,
+ private maxBatchSize: number = DEFAULT_MAX_BATCH_SIZE
+ ) {}
+
+ public execute(bytecode: unknown[], globals: unknown): Promise<RustExecResult> {
+ return new Promise((resolve, reject) => {
+ let queue = this.queues.get(bytecode)
+ if (!queue) {
+ queue = []
+ this.queues.set(bytecode, queue)
+ }
+ queue.push({ globals, resolve, reject })
+
+ if (queue.length >= this.maxBatchSize) {
+ this.queues.delete(bytecode)
+ this.dispatch(bytecode, queue)
+ return
+ }
+
+ if (!this.flushScheduled) {
+ this.flushScheduled = true
+ setImmediate(() => this.flush())
+ }
+ })
+ }
+
+ private flush(): void {
+ this.flushScheduled = false
+ const queues = this.queues
+ this.queues = new Map()
+ for (const [bytecode, entries] of queues) {
+ this.dispatch(bytecode, entries)
+ }
+ }
+
+ private dispatch(bytecode: unknown[], entries: QueueEntry[]): void {
+ hogvmRustBatchFlushSize.observe(entries.length)
+ this.runBatch(
+ bytecode,
+ entries.map((entry) => entry.globals)
+ )
+ .then((results) => {
+ if (results.length !== entries.length) {
+ throw new Error(`executeBatch returned ${results.length} results for ${entries.length} events`)
+ }
+ entries.forEach((entry, index) => entry.resolve(results[index]))
+ })
+ .catch((error) => {
+ entries.forEach((entry) => entry.reject(error))
+ })
+ }
+}
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 a04d0848d0d1..2a44b3bb6593 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
@@ -7,6 +7,7 @@ import { RustVmExecutor } from './rust-vm-executor'
jest.mock('@posthog/hogvm-node', () => ({
init: jest.fn(),
executeSync: jest.fn(),
+ executeBatch: jest.fn(),
}))
const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
@@ -134,4 +135,59 @@ describe('RustVmExecutor', () => {
expect(executor.execute(createExampleInvocation(), [])).toBeNull()
expect(mockHogvmNode.executeSync).not.toHaveBeenCalled()
})
+
+ describe('executeBatched', () => {
+ beforeEach(() => {
+ // clearAllMocks doesn't clear implementations: without this, the sync-path
+ // "addon unavailable" test's throwing init would leak into these tests.
+ mockHogvmNode.init.mockImplementation(() => {})
+ })
+
+ it('runs the invocation through executeBatch off the JS thread and maps the result like the sync path', async () => {
+ const invocation = createExampleInvocation({ bytecode: ['_H', 1, 38] })
+ mockHogvmNode.executeBatch.mockResolvedValue([rustResult()])
+
+ const result = await executor.executeBatched(invocation, [])
+
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledWith(['_H', 1, 38], [invocation.state.globals], {
+ parallel: true,
+ maxSteps: 1_000_000,
+ })
+ expect(result!.finished).toEqual(true)
+ expect(result!.execResult).toEqual({ properties: { a: 1 } })
+ expect(result!.invocation.state.timings).toEqual([{ kind: 'hog', duration_ms: 1.5 }])
+ })
+
+ it('a marshal error means the event never executed, so it alone falls back to the node vm', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ rustResult({ result: undefined, error: 'marshal_error:Failed to convert js number' }),
+ ])
+
+ expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ })
+
+ it('falls back to the node vm on unsupported-program errors, same predicate as the sync path', async () => {
+ mockHogvmNode.executeBatch.mockResolvedValue([
+ rustResult({ result: undefined, error: 'Native call failed: unsupported_ext_fn:geoipLookup' }),
+ ])
+
+ expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ })
+
+ it('falls back to the node vm when the whole batch call rejects', async () => {
+ mockHogvmNode.executeBatch.mockRejectedValue(new Error('native fault'))
+
+ expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ })
+
+ it('falls back to the node vm when the native addon is unavailable, without enqueueing', async () => {
+ mockHogvmNode.init.mockImplementation(() => {
+ throw new Error('addon not built')
+ })
+
+ expect(await executor.executeBatched(createExampleInvocation(), [])).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
index 2faad4606c1f..2e9330b588a3 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
@@ -6,7 +6,15 @@ import { logger } from '~/common/utils/logger'
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'
+import {
+ HogvmNodeModule,
+ MARSHAL_ERROR_PREFIX,
+ RUST_MAX_STEPS,
+ RustExecResult,
+ isUnsupportedByRustVm,
+ loadHogvmNodeModule,
+} from './rust-vm'
+import { RustVmBatchScheduler } from './rust-vm-batch-scheduler'
/**
* Executes transformation invocations on the Rust HogVM (via the `@posthog/hogvm-node` napi
@@ -14,6 +22,11 @@ import { HogvmNodeModule, RUST_MAX_STEPS, isUnsupportedByRustVm, loadHogvmNodeMo
* 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.
+ *
+ * Two execution paths: `execute` runs one invocation synchronously on the JS thread
+ * (`executeSync`); `executeBatched` enqueues into a {@link RustVmBatchScheduler} that coalesces
+ * same-program invocations into one `executeBatch` FFI crossing per tick, executed off the JS
+ * event loop.
*/
export const rustVmExecution = new Counter({
@@ -29,7 +42,18 @@ export const rustVmExecutionDuration = new Histogram({
})
export class RustVmExecutor {
- constructor(private options: { mmdbPath: string }) {}
+ private scheduler: RustVmBatchScheduler
+
+ constructor(private options: { mmdbPath: string }) {
+ this.scheduler = new RustVmBatchScheduler((program, events) => {
+ const module_ = this.getModule()
+ if (!module_) {
+ // Unreachable in practice: executeBatched checks the module before enqueueing.
+ return Promise.reject(new Error('Rust HogVM native module unavailable'))
+ }
+ return module_.executeBatch(program, events, { parallel: true, maxSteps: RUST_MAX_STEPS })
+ })
+ }
private getModule(): HogvmNodeModule | null {
return loadHogvmNodeModule({ mmdbPath: this.options.mmdbPath })
@@ -63,8 +87,7 @@ export class RustVmExecutor {
*
* 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.
+ * libuv thread-hop per invocation would cost more than the execution it offloads.
*/
public execute(
invocation: CyclotronJobInvocationHogFunction,
@@ -93,6 +116,46 @@ export class RustVmExecutor {
return this.fallback('fallback_exception', invocation, sensitiveValues, error)
}
+ return this.toInvocationResult(rust, invocation, sensitiveValues)
+ }
+
+ /**
+ * Execute one transformation invocation via the batching scheduler: same-program invocations
+ * in flight during the same tick share one `executeBatch` call, off the JS event loop.
+ * Returns null when the Node VM must run it instead — same fallback contract as `execute`,
+ * with a batch event that failed JS→JSON conversion (`marshal_error:`) treated like the sync
+ * path's boundary throw: that event alone falls back, having never executed.
+ */
+ public async executeBatched(
+ invocation: CyclotronJobInvocationHogFunction,
+ sensitiveValues: string[]
+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null> {
+ const module_ = this.getModule()
+ if (!module_) {
+ rustVmExecution.inc({ outcome: 'fallback_unavailable' })
+ return null
+ }
+
+ let rust: RustExecResult
+ try {
+ rust = await this.scheduler.execute(invocation.hogFunction.bytecode, invocation.state.globals)
+ } catch (error) {
+ // A rejected batch never delivered results, so nothing executed — safe to fall back.
+ return this.fallback('fallback_exception', invocation, sensitiveValues, error)
+ }
+
+ if (rust.error?.startsWith(MARSHAL_ERROR_PREFIX)) {
+ return this.fallback('fallback_exception', invocation, sensitiveValues, rust.error)
+ }
+
+ return this.toInvocationResult(rust, invocation, sensitiveValues)
+ }
+
+ private toInvocationResult(
+ rust: RustExecResult,
+ invocation: CyclotronJobInvocationHogFunction,
+ sensitiveValues: string[]
+ ): CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> | null {
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.ts b/nodejs/src/cdp/hog-transformations/rust-vm.ts
index c4b75a79a372..fcd3cdf3b7e9 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm.ts
@@ -22,6 +22,11 @@ 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 '
+// A batch event whose globals couldn't cross the napi boundary (e.g. NaN/Infinity) never
+// executed; like a boundary throw on the sync path, that event falls back to the Node VM
+// (rust/common/hogvm/node/src/exec.rs `MARSHAL_ERROR_PREFIX`).
+export const MARSHAL_ERROR_PREFIX = 'marshal_error:'
+
/**
* 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. Real execution errors must never match — the
@@ -48,6 +53,11 @@ export interface RustExecResult {
export interface HogvmNodeModule {
init(options: { mmdbPath?: string; knownBotUaList?: string[]; knownBotIpList?: string[] }): void
executeSync(program: unknown[], globals: unknown, options?: { maxSteps?: number }): RustExecResult
+ executeBatch(
+ program: unknown[],
+ events: unknown[],
+ options?: { parallel?: boolean; maxSteps?: number }
+ ): Promise<RustExecResult[]>
}
let cachedModule: HogvmNodeModule | null | undefined = undefined
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 37d0c6012633..8d36b85601c9 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -228,6 +228,11 @@ export type CommonConfig = BaseServerConfig & {
// can't run (unsupported host functions, addon not built) fall back to the Node VM.
CDP_HOG_RUST_VM_EXECUTION_ENABLED: boolean
+ // With the Rust VM enabled, coalesce concurrent same-program invocations into one
+ // executeBatch FFI call per tick, executed off the JS event loop, instead of per-invocation
+ // executeSync on the JS thread.
+ CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED: boolean
+
/** Per-function wall-clock budget for an event transformation, enforced by the HogVM. */
TRANSFORMATIONS_HOG_TIMEOUT_MS: number
@@ -415,6 +420,7 @@ export function getDefaultCommonConfig(): CommonConfig {
// Shared between ingestion and CDP
CDP_HOG_RUST_VM_EXECUTION_ENABLED: false,
+ CDP_HOG_RUST_VM_BATCH_EXECUTION_ENABLED: false,
TRANSFORMATIONS_HOG_TIMEOUT_MS: 300,
// Event loop yield helper
diff --git a/rust/common/hogvm/node/Cargo.lock b/rust/common/hogvm/node/Cargo.lock
index c31e0861aae3..8832a78ae170 100644
--- a/rust/common/hogvm/node/Cargo.lock
+++ b/rust/common/hogvm/node/Cargo.lock
@@ -130,6 +130,31 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -161,6 +186,12 @@ 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"
@@ -280,6 +311,7 @@ dependencies = [
"napi",
"napi-build",
"napi-derive",
+ "rayon",
"serde_json",
]
@@ -598,6 +630,26 @@ 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 ead9fe1ce5a0..cb501de8ed23 100644
--- a/rust/common/hogvm/node/Cargo.toml
+++ b/rust/common/hogvm/node/Cargo.toml
@@ -21,6 +21,7 @@ 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 0aabc8d7150d..bb6eafb083b9 100644
--- a/rust/common/hogvm/node/index.d.ts
+++ b/rust/common/hogvm/node/index.d.ts
@@ -23,6 +23,13 @@ export interface ExecuteSyncOptions {
maxSteps?: number
}
+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
+}
+
/**
* Load process-wide state for the transformation host functions. Idempotent; only the first call
* takes effect.
@@ -35,3 +42,15 @@ export function init(options: InitOptions): void
* exec, with no threadpool round-trip.
*/
export function executeSync(program: unknown[], globals: unknown, options?: ExecuteSyncOptions): HogExecResult
+
+/**
+ * Run one Hog program (bytecode tokens) against many event-globals, off the JS event loop,
+ * crossing the FFI boundary once for the whole batch. Returns one result per event, in input
+ * order. An event whose globals can't be converted to JSON (e.g. NaN/Infinity numbers) gets a
+ * `marshal_error:`-prefixed error result instead of rejecting the whole call.
+ */
+export function executeBatch(
+ program: unknown[],
+ events: unknown[],
+ options?: ExecuteBatchOptions
+): Promise<HogExecResult[]>
diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rs
index 74551dd1164a..b74e5d1eb118 100644
--- a/rust/common/hogvm/node/src/exec.rs
+++ b/rust/common/hogvm/node/src/exec.rs
@@ -4,15 +4,25 @@ 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;
+// Floor on the derived rayon chunk size: each chunk rebuilds the Program and ExecutionContext
+// (STL + ext fns), so chunks need enough events to amortize that setup.
+const MIN_PARALLEL_CHUNK_SIZE: usize = 50;
+
// The Node VM has no heap ceiling; the crate's 1MB default trips on real events with large
-// properties. A cap, not a preallocation.
+// properties. A cap (not a preallocation), and rayon bounds how many contexts run at once.
const MAX_HEAP_SIZE_BYTES: usize = 64 * 1024 * 1024;
+/// Prefix marking an event whose globals could not be converted at the napi boundary (e.g.
+/// NaN/Infinity numbers, which serde_json can't represent). Contract with the Node caller: these
+/// mean "this event never executed", so it alone falls back to the Node VM.
+pub const MARSHAL_ERROR_PREFIX: &str = "marshal_error:";
+
#[napi(object)]
pub struct HogExecResult {
/// The program's return value; None when the execution errored.
@@ -28,6 +38,7 @@ pub struct HogExecResult {
pub fn run_batch(
tokens: &[Value],
events: &[Value],
+ parallel: bool,
max_steps: Option<usize>,
) -> Vec<HogExecResult> {
if tokens.is_empty() {
@@ -37,11 +48,58 @@ pub fn run_batch(
.collect();
}
- run_chunk(tokens, events, max_steps)
+ if !parallel {
+ return run_chunk(tokens, events, max_steps);
+ }
+
+ // Chunk size follows the batch so any batch worth parallelizing splits across the rayon
+ // pool; a fixed size tied to the caller's max batch size would put the whole batch in one
+ // chunk and never fan out.
+ let chunk_size = events
+ .len()
+ .div_ceil(rayon::current_num_threads())
+ .max(MIN_PARALLEL_CHUNK_SIZE);
+ events
+ .par_chunks(chunk_size)
+ .flat_map_iter(|chunk| run_chunk(tokens, chunk, max_steps).into_iter())
+ .collect()
}
-// Run the events through one reused ExecutionContext (STL and ext fns built once, globals
-// swapped per event), sequentially on the calling thread.
+/// Like [`run_batch`], but tolerates events whose JS→JSON conversion failed at the napi boundary:
+/// an `Err(reason)` event gets a `marshal_error:<reason>` result and only the converted events
+/// execute, so one unrepresentable event can't fail the whole batch. Results stay in input order.
+pub fn run_batch_salvaged(
+ tokens: &[Value],
+ events: Vec<Result<Value, String>>,
+ parallel: bool,
+ max_steps: Option<usize>,
+) -> Vec<HogExecResult> {
+ let mut ok_events = Vec::with_capacity(events.len());
+ let mut slots: Vec<Option<String>> = Vec::with_capacity(events.len());
+ for event in events {
+ match event {
+ Ok(value) => {
+ ok_events.push(value);
+ slots.push(None);
+ }
+ Err(reason) => slots.push(Some(reason)),
+ }
+ }
+
+ let mut executed = run_batch(tokens, &ok_events, parallel, max_steps).into_iter();
+ slots
+ .into_iter()
+ .map(|slot| match slot {
+ Some(reason) => error_result(&format!("{MARSHAL_ERROR_PREFIX}{reason}"), 0.0),
+ None => executed
+ .next()
+ .expect("run_batch returns one result per event"),
+ })
+ .collect()
+}
+
+// Run a slice of events through one reused ExecutionContext (STL and ext fns built once, globals
+// swapped per event).
fn run_chunk(tokens: &[Value], chunk: &[Value], max_steps: Option<usize>) -> Vec<HogExecResult> {
let program = match Program::new(tokens.to_vec()) {
Ok(p) => p,
@@ -150,24 +208,45 @@ mod tests {
]
}
+ // print(globals.<global>) (POP the call result), then return 1+2
+ fn print_global_program(global: &str) -> Vec<Value> {
+ let mut program = vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!(global),
+ json!(1),
+ json!(1),
+ json!(2),
+ json!("print"),
+ json!(1),
+ json!(35),
+ ];
+ program.extend(add_program().into_iter().skip(2));
+ program
+ }
+
#[test]
fn executes_each_event_with_its_own_globals_in_order() {
+ // Enough events for several rayon chunks in the parallel case.
let events: Vec<Value> = (0..1200)
.map(|i| json!({ "name": i.to_string() }))
.collect();
- 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);
+ 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);
+ }
}
}
#[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, None);
+ let results = run_batch(&get_global_program("name"), &events, false, None);
assert_eq!(results[0].result, Some(json!("ok")));
assert!(results[1].result.is_none());
assert!(results[1].error.as_deref().unwrap().contains("name"));
@@ -175,7 +254,12 @@ mod tests {
#[test]
fn invalid_program_errors_every_event() {
- let results = run_batch(&[json!("not bytecode")], &[json!({}), json!({})], None);
+ let results = run_batch(
+ &[json!("not bytecode")],
+ &[json!({}), json!({})],
+ false,
+ None,
+ );
assert_eq!(results.len(), 2);
for r in &results {
assert!(r.error.as_deref().unwrap().starts_with("invalid program"));
@@ -184,10 +268,40 @@ mod tests {
#[test]
fn empty_program_errors_every_event() {
- let results = run_batch(&[], &[json!({})], None);
+ let results = run_batch(&[], &[json!({})], false, None);
assert!(results[0].error.is_some());
}
+ #[test]
+ fn salvaged_batch_interleaves_marshal_errors_in_input_order() {
+ let events = vec![
+ Ok(json!({ "name": "a" })),
+ Err("nan in globals".to_string()),
+ Ok(json!({ "name": "b" })),
+ ];
+ let results = run_batch_salvaged(&get_global_program("name"), events, false, None);
+ assert_eq!(results.len(), 3);
+ assert_eq!(results[0].result, Some(json!("a")));
+ assert_eq!(
+ results[1].error.as_deref(),
+ Some("marshal_error:nan in globals")
+ );
+ assert_eq!(results[1].duration_us, 0.0);
+ assert_eq!(results[2].result, Some(json!("b")));
+ }
+
+ #[test]
+ fn salvaged_batch_with_all_marshal_errors_executes_nothing() {
+ let events = vec![Err("x".to_string()), Err("y".to_string())];
+ let results = run_batch_salvaged(&add_program(), events, false, None);
+ assert_eq!(results.len(), 2);
+ assert!(results.iter().all(|r| r
+ .error
+ .as_deref()
+ .unwrap()
+ .starts_with(MARSHAL_ERROR_PREFIX)));
+ }
+
#[test]
fn comparisons_coerce_booleans_and_nulls_like_the_reference() {
// rev > 0 where rev is boolean (or-chains yield booleans): true coerces to 1.
@@ -200,7 +314,7 @@ mod tests {
json!(13),
json!(38),
];
- let results = run_batch(&gt_true_zero, &[json!({})], None);
+ let results = run_batch(&gt_true_zero, &[json!({})], false, None);
assert_eq!(results[0].error, None);
assert_eq!(results[0].result, Some(json!(true)));
@@ -214,22 +328,27 @@ mod tests {
json!(15),
json!(38),
];
- let results = run_batch(&lt_zero_null, &[json!({})], None);
+ let results = run_batch(&lt_zero_null, &[json!({})], false, 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!({})], Some(1));
+ let results = run_batch(&add_program(), &[json!({})], false, Some(1));
assert!(results[0].error.is_some());
- let results = run_batch(&add_program(), &[json!({})], None);
+ let results = run_batch(&add_program(), &[json!({})], false, 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!({})], None);
+ let results = run_batch(
+ &call_fn_program("postHogCapture", "x"),
+ &[json!({})],
+ false,
+ None,
+ );
assert!(results[0]
.error
.as_deref()
@@ -242,6 +361,7 @@ mod tests {
let results = run_batch(
&call_fn_program("generateMessagingPreferencesUrl", "x"),
&[json!({})],
+ false,
None,
);
assert!(results[0]
@@ -257,6 +377,7 @@ mod tests {
let results = run_batch(
&call_fn_program("geoipLookup", "89.160.20.129"),
&[json!({})],
+ false,
None,
);
assert!(results[0]
@@ -274,6 +395,7 @@ mod tests {
let results = run_batch(
&call_fn_program("someFunctionNobodyImplements", "x"),
&[json!({})],
+ false,
None,
);
assert!(results[0]
@@ -282,7 +404,7 @@ mod tests {
.unwrap()
.starts_with("Unknown function "));
- let results = run_batch(&get_global_program("missing"), &[json!({})], None);
+ let results = run_batch(&get_global_program("missing"), &[json!({})], false, None);
assert!(results[0]
.error
.as_deref()
@@ -304,7 +426,7 @@ mod tests {
json!(35),
];
program.extend(add_program().into_iter().skip(2));
- let results = run_batch(&program, &[json!({})], None);
+ 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()]);
@@ -314,24 +436,28 @@ mod tests {
// 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 program = print_global_program("g");
let events = vec![json!({ "g": { "a": 1 } }), json!({ "g": "plain" })];
- let results = run_batch(&program, &events, None);
+ 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()]);
}
+ #[test]
+ fn parallel_execution_does_not_mix_print_logs_across_events() {
+ // Enough events for several 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.
@@ -347,7 +473,7 @@ mod tests {
]);
}
program.extend(add_program().into_iter().skip(2));
- let results = run_batch(&program, &[json!({})], None);
+ 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);
@@ -355,7 +481,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!({})], None);
+ let results = run_batch(&add_program(), &[json!({})], false, None);
assert_eq!(results[0].logs, Vec::<String>::new());
assert!(!results[0].logs_truncated);
}
@@ -366,12 +492,14 @@ 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)));
@@ -383,12 +511,14 @@ 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)));
@@ -399,6 +529,7 @@ mod tests {
let results = run_batch(
&call_fn_program("cleanNullValues", "unused"),
&[json!({})],
+ false,
None,
);
// A string arg passes through untouched.
@@ -420,6 +551,7 @@ 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 af214c4ad787..5d0f3a3a079a 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 executing ingestion transformations.
//!
-//! `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.
+//! Two entry points: `executeSync` runs one (bytecode, globals) pair synchronously on the calling
+//! thread — the per-event execution path, matching the Node VM's synchronous exec with no
+//! threadpool round-trip. `executeBatch` runs one program against many event-globals, crossing
+//! the FFI boundary once per batch, off the JS event loop (libuv worker via `AsyncTask`), and can
+//! fan out over a rayon thread pool.
//!
//! Transformation host functions (`geoipLookup`, `cleanNullValues`, `isKnownBotUserAgent`,
//! `isKnownBotIp`) mirror `nodejs/src/cdp/hog-transformations/transformation-functions.ts`; call
@@ -16,11 +17,15 @@ mod ext_fns;
mod geoip;
mod logs;
+#[cfg(not(feature = "noop"))]
+use napi::bindgen_prelude::{AsyncTask, FromNapiValue};
use napi::Result as NapiResult;
+#[cfg(not(feature = "noop"))]
+use napi::{Env, JsUnknown, NapiRaw, Task};
use napi_derive::napi;
use serde_json::Value;
-pub use exec::{run_batch, HogExecResult};
+pub use exec::{run_batch, run_batch_salvaged, HogExecResult, MARSHAL_ERROR_PREFIX};
#[napi(object)]
pub struct InitOptions {
@@ -40,6 +45,85 @@ 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<Result<Value, String>>,
+ parallel: bool,
+ max_steps: Option<usize>,
+}
+
+// The `noop` test build strips the generated ToNapiValue impls the Task bound needs; tests
+// exercise `run_batch`/`run_batch_salvaged` 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_salvaged(
+ &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. An event whose globals can't be
+/// converted to JSON (e.g. NaN/Infinity numbers) gets a `marshal_error:`-prefixed error result
+/// instead of rejecting the whole call.
+#[cfg(not(feature = "noop"))]
+#[napi(ts_return_type = "Promise<Array<HogExecResult>>")]
+pub fn execute_batch(
+ env: Env,
+ program: Value,
+ events: Vec<JsUnknown>,
+ options: Option<ExecuteBatchOptions>,
+) -> AsyncTask<ExecuteBatchTask> {
+ let tokens = match program {
+ Value::Array(tokens) => tokens,
+ _ => Vec::new(),
+ };
+ // Convert on the JS thread (JS values can't cross to the worker), one event at a time so an
+ // unrepresentable value poisons only its own event, not the batch. Must be the same strict
+ // conversion `executeSync`'s arguments go through (throws on NaN/Infinity) — not
+ // `Env::from_js_value`, which silently coerces non-finite numbers to null and would give
+ // these events different semantics than the sync path's Node VM fallback.
+ let events = events
+ .into_iter()
+ .map(|event| {
+ // nosemgrep: rust.lang.security.unsafe-usage.unsafe-usage
+ unsafe { Value::from_napi_value(env.raw(), event.raw()) }.map_err(|e| e.reason)
+ })
+ .collect();
+ let (parallel, max_steps) = match options {
+ Some(o) => (o.parallel.unwrap_or(false), o.max_steps.map(|m| m as usize)),
+ None => (false, None),
+ };
+ AsyncTask::new(ExecuteBatchTask {
+ tokens,
+ events,
+ parallel,
+ max_steps,
+ })
+}
+
#[napi(object)]
pub struct ExecuteSyncOptions {
/// Step budget for the execution (the Rust VM has no wall-clock timeout).
@@ -47,7 +131,7 @@ pub struct ExecuteSyncOptions {
}
/// 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
+/// per-event execution path for ingestion transformations: it matches the Node VM's synchronous
/// exec, with no threadpool round-trip.
#[napi]
pub fn execute_sync(
@@ -60,7 +144,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), max_steps)
+ run_batch(&tokens, std::slice::from_ref(&globals), false, max_steps)
.into_iter()
.next()
.expect("run_batch returns one result per event")