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.

perf(hogvm): register transformation programs once instead of per event (#74120)

José Sequeiraaa436fd9c95a
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts
index e79c00fc8c14..75c105830d44 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-batch-scheduler.ts
@@ -1,7 +1,6 @@
-import { createHash } from 'crypto'
import { Histogram } from 'prom-client'
-import { RustExecResult } from './rust-vm'
+import { RustExecResult, programKey } from './rust-vm'
export const hogvmRustBatchFlushSize = new Histogram({
name: 'hogvm_rust_batch_flush_size',
@@ -46,9 +45,6 @@ export const DEFAULT_MAX_BATCH_SIZE = 500
*/
export class RustVmBatchScheduler {
private queues = new Map<string, ProgramQueue>()
- // Content hash per array instance. The hog function manager hands out one cached array per
- // function, so this is computed once per function, not once per invocation.
- private programKeys = new WeakMap<unknown[], string>()
private flushScheduled = false
constructor(
@@ -58,7 +54,7 @@ export class RustVmBatchScheduler {
public execute(bytecode: unknown[], globals: unknown): Promise<RustExecResult> {
return new Promise((resolve, reject) => {
- const key = this.programKey(bytecode)
+ const key = programKey(bytecode)
let queue = this.queues.get(key)
if (!queue) {
queue = { bytecode, entries: [] }
@@ -79,15 +75,6 @@ export class RustVmBatchScheduler {
})
}
- private programKey(bytecode: unknown[]): string {
- let key = this.programKeys.get(bytecode)
- if (key === undefined) {
- key = createHash('sha256').update(JSON.stringify(bytecode)).digest('base64')
- this.programKeys.set(bytecode, key)
- }
- return key
- }
-
private flush(): void {
this.flushScheduled = false
const queues = this.queues
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 2a44b3bb6593..e1e8d7ca5ff7 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.test.ts
@@ -2,12 +2,16 @@ import { logger } from '~/common/utils/logger'
import { createExampleInvocation } from '../_tests/fixtures'
import { resetHogvmNodeModuleCacheForTests } from './rust-vm'
-import { RustVmExecutor } from './rust-vm-executor'
+import { MAX_REGISTERED_PROGRAMS, RustVmExecutor } from './rust-vm-executor'
jest.mock('@posthog/hogvm-node', () => ({
init: jest.fn(),
executeSync: jest.fn(),
executeBatch: jest.fn(),
+ registerProgram: jest.fn(),
+ releaseProgram: jest.fn(),
+ executeRegisteredSync: jest.fn(),
+ executeRegisteredBatch: jest.fn(),
}))
const mockHogvmNode = jest.mocked(jest.requireMock<typeof import('@posthog/hogvm-node')>('@posthog/hogvm-node'))
@@ -20,24 +24,52 @@ const rustResult = (overrides: Partial<ReturnType<typeof mockHogvmNode.executeSy
...overrides,
})
+// Distinct bytecode per value: "_H" header, version 1, push int, RETURN.
+const program = (value: number): unknown[] => ['_H', 1, 33, value, 38]
+
+const withoutBinding = async (binding: keyof typeof mockHogvmNode, run: () => Promise<void> | void): Promise<void> => {
+ const original = mockHogvmNode[binding]
+ delete mockHogvmNode[binding]
+ try {
+ await run()
+ } finally {
+ Object.assign(mockHogvmNode, { [binding]: original })
+ }
+}
+
describe('RustVmExecutor', () => {
let executor: RustVmExecutor
+ let nextHandle = 0
beforeEach(() => {
jest.clearAllMocks()
resetHogvmNodeModuleCacheForTests()
executor = new RustVmExecutor({ mmdbPath: '/dev/null' })
+ // `clearAllMocks` resets call data but not implementations, so a case that makes a mock
+ // throw would leak into every case after it. Re-establish the working defaults here.
+ nextHandle = 0
+ mockHogvmNode.init.mockImplementation(() => {})
+ mockHogvmNode.registerProgram.mockImplementation(() => nextHandle++)
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(rustResult())
+ mockHogvmNode.executeSync.mockReturnValue(rustResult())
+ mockHogvmNode.executeRegisteredBatch.mockImplementation((_handle, events) =>
+ Promise.resolve(events.map(() => rustResult()))
+ )
+ mockHogvmNode.executeBatch.mockImplementation((_bytecode, events) =>
+ Promise.resolve(events.map(() => rustResult()))
+ )
})
- it('executes the invocation bytecode against its globals and returns a finished result', () => {
+ it('registers the invocation bytecode, executes it by handle against the globals and returns a finished result', () => {
const invocation = createExampleInvocation({ bytecode: ['_H', 1, 38] })
- mockHogvmNode.executeSync.mockReturnValue(rustResult())
const result = executor.execute(invocation, [])
- expect(mockHogvmNode.executeSync).toHaveBeenCalledWith(['_H', 1, 38], invocation.state.globals, {
+ expect(mockHogvmNode.registerProgram).toHaveBeenCalledWith(['_H', 1, 38])
+ expect(mockHogvmNode.executeRegisteredSync).toHaveBeenCalledWith(0, 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()
@@ -47,7 +79,7 @@ describe('RustVmExecutor', () => {
})
it('a null program result leaves execResult unset so the transformer drops the event', () => {
- mockHogvmNode.executeSync.mockReturnValue(rustResult({ result: null }))
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(rustResult({ result: null }))
const result = executor.execute(createExampleInvocation(), [])
@@ -56,7 +88,7 @@ describe('RustVmExecutor', () => {
})
it('surfaces print() output as info logs with sensitive values redacted, plus a truncation warning', () => {
- mockHogvmNode.executeSync.mockReturnValue(
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(
rustResult({ logs: ['token is secret-token', 'plain'], logsTruncated: true })
)
@@ -71,7 +103,7 @@ describe('RustVmExecutor', () => {
})
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'] }))
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(rustResult({ logs: ['token is secret-a and secret-b'] }))
const first = executor.execute(createExampleInvocation(), ['secret-a'])
const second = executor.execute(createExampleInvocation(), ['secret-b'])
@@ -81,7 +113,9 @@ describe('RustVmExecutor', () => {
})
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' }))
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(
+ rustResult({ result: undefined, error: 'Division by zero' })
+ )
const result = executor.execute(createExampleInvocation(), [])
@@ -98,14 +132,14 @@ describe('RustVmExecutor', () => {
['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', (_name, error) => {
- mockHogvmNode.executeSync.mockReturnValue(rustResult({ result: undefined, error }))
+ mockHogvmNode.executeRegisteredSync.mockReturnValue(rustResult({ result: undefined, error }))
expect(executor.execute(createExampleInvocation(), [])).toBeNull()
})
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.executeSync.mockImplementation(() => {
+ mockHogvmNode.executeRegisteredSync.mockImplementation(() => {
throw new Error('Failed to convert js number to serde_json::Number')
})
@@ -115,7 +149,7 @@ describe('RustVmExecutor', () => {
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.executeSync.mockImplementation(() => {
+ mockHogvmNode.executeRegisteredSync.mockImplementation(() => {
throw new Error('failed to convert value "secret-token" at inputs')
})
@@ -133,42 +167,38 @@ describe('RustVmExecutor', () => {
})
expect(executor.execute(createExampleInvocation(), [])).toBeNull()
- expect(mockHogvmNode.executeSync).not.toHaveBeenCalled()
+ expect(mockHogvmNode.registerProgram).not.toHaveBeenCalled()
+ expect(mockHogvmNode.executeRegisteredSync).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 () => {
+ it('runs the invocation through executeRegisteredBatch 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], {
+ expect(mockHogvmNode.registerProgram).toHaveBeenCalledWith(['_H', 1, 38])
+ expect(mockHogvmNode.executeRegisteredBatch).toHaveBeenCalledWith(0, [invocation.state.globals], {
parallel: true,
maxSteps: 1_000_000,
})
+ expect(mockHogvmNode.executeBatch).not.toHaveBeenCalled()
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([
+ mockHogvmNode.executeRegisteredBatch.mockResolvedValue([
rustResult({ result: undefined, error: 'marshal_error:Failed to convert js number' }),
])
expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
- expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeRegisteredBatch).toHaveBeenCalledTimes(1)
})
it('falls back to the node vm on unsupported-program errors, same predicate as the sync path', async () => {
- mockHogvmNode.executeBatch.mockResolvedValue([
+ mockHogvmNode.executeRegisteredBatch.mockResolvedValue([
rustResult({ result: undefined, error: 'Native call failed: unsupported_ext_fn:geoipLookup' }),
])
@@ -176,9 +206,18 @@ describe('RustVmExecutor', () => {
})
it('falls back to the node vm when the whole batch call rejects', async () => {
- mockHogvmNode.executeBatch.mockRejectedValue(new Error('native fault'))
+ mockHogvmNode.executeRegisteredBatch.mockRejectedValue(new Error('native fault'))
+
+ expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ })
+
+ it('falls back to the node vm when registering the program throws during dispatch', async () => {
+ mockHogvmNode.registerProgram.mockImplementation(() => {
+ throw new Error('addon panicked')
+ })
expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ expect(mockHogvmNode.executeRegisteredBatch).not.toHaveBeenCalled()
})
it('falls back to the node vm when the native addon is unavailable, without enqueueing', async () => {
@@ -187,7 +226,107 @@ describe('RustVmExecutor', () => {
})
expect(await executor.executeBatched(createExampleInvocation(), [])).toBeNull()
+ expect(mockHogvmNode.executeRegisteredBatch).not.toHaveBeenCalled()
expect(mockHogvmNode.executeBatch).not.toHaveBeenCalled()
})
})
+
+ describe('registered programs', () => {
+ it('registers identical bytecode once and shares the handle across events and hog functions', () => {
+ executor.execute(createExampleInvocation({ id: 'fn-1', bytecode: program(1) }), [])
+ executor.execute(createExampleInvocation({ id: 'fn-2', bytecode: program(1) }), [])
+
+ expect(mockHogvmNode.registerProgram).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeRegisteredSync.mock.calls.map((call) => call[0])).toEqual([0, 0])
+ })
+
+ it('registers edited bytecode as a new program instead of reusing the handle of the old one', () => {
+ executor.execute(createExampleInvocation({ id: 'fn-1', bytecode: program(1) }), [])
+ executor.execute(createExampleInvocation({ id: 'fn-1', bytecode: program(2) }), [])
+
+ expect(mockHogvmNode.registerProgram).toHaveBeenCalledTimes(2)
+ expect(mockHogvmNode.executeRegisteredSync).toHaveBeenLastCalledWith(1, expect.anything(), {
+ maxSteps: 1_000_000,
+ })
+ })
+
+ it('releases a handle once the cache is full so the rust registry stays bounded', () => {
+ for (let i = 0; i < MAX_REGISTERED_PROGRAMS; i++) {
+ executor.execute(createExampleInvocation({ bytecode: program(i) }), [])
+ }
+ expect(mockHogvmNode.releaseProgram).not.toHaveBeenCalled()
+
+ executor.execute(createExampleInvocation({ bytecode: program(MAX_REGISTERED_PROGRAMS) }), [])
+
+ expect(mockHogvmNode.releaseProgram).toHaveBeenCalledTimes(1)
+ })
+
+ it('evicts the least recently used program, keeping a hot one registered', () => {
+ const hot = createExampleInvocation({ bytecode: program(0) })
+ for (let i = 0; i < MAX_REGISTERED_PROGRAMS; i++) {
+ executor.execute(createExampleInvocation({ bytecode: program(i) }), [])
+ }
+ const hotHandle = mockHogvmNode.executeRegisteredSync.mock.calls[0][0]
+
+ executor.execute(hot, [])
+ executor.execute(createExampleInvocation({ bytecode: program(MAX_REGISTERED_PROGRAMS) }), [])
+
+ expect(mockHogvmNode.releaseProgram).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.releaseProgram).not.toHaveBeenCalledWith(hotHandle)
+
+ mockHogvmNode.registerProgram.mockClear()
+ executor.execute(hot, [])
+ expect(mockHogvmNode.registerProgram).not.toHaveBeenCalled()
+ expect(mockHogvmNode.executeRegisteredSync).toHaveBeenLastCalledWith(hotHandle, expect.anything(), {
+ maxSteps: 1_000_000,
+ })
+ })
+
+ it.each(['registerProgram', 'releaseProgram', 'executeRegisteredSync'] as const)(
+ 'executes unregistered when the addon lacks %s instead of throwing on every invocation',
+ async (binding) => {
+ await withoutBinding(binding, () => {
+ const result = executor.execute(createExampleInvocation({ bytecode: program(1) }), [])
+
+ expect(result).not.toBeNull()
+ expect(result!.error).toBeUndefined()
+ expect(mockHogvmNode.executeSync).toHaveBeenCalledTimes(1)
+ expect(nextHandle).toEqual(0)
+ })
+ }
+ )
+
+ it('batches through executeRegisteredBatch, registering the program once across flushes', async () => {
+ const invocation = createExampleInvocation({ bytecode: program(1) })
+
+ const first = await executor.executeBatched(invocation, [])
+ const second = await executor.executeBatched(invocation, [])
+
+ expect(mockHogvmNode.registerProgram).toHaveBeenCalledTimes(1)
+ expect(mockHogvmNode.executeRegisteredBatch).toHaveBeenCalledTimes(2)
+ expect(mockHogvmNode.executeRegisteredBatch).toHaveBeenLastCalledWith(0, [invocation.state.globals], {
+ parallel: true,
+ maxSteps: 1_000_000,
+ })
+ expect(first!.error).toBeUndefined()
+ expect(second!.error).toBeUndefined()
+ })
+
+ it('batch falls back to executeBatch when the addon lacks executeRegisteredBatch', async () => {
+ const invocation = createExampleInvocation({ bytecode: program(1) })
+
+ await withoutBinding('executeRegisteredBatch', async () => {
+ const result = await executor.executeBatched(invocation, [])
+
+ expect(result).not.toBeNull()
+ expect(result!.error).toBeUndefined()
+ expect(mockHogvmNode.registerProgram).not.toHaveBeenCalled()
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledWith(
+ invocation.hogFunction.bytecode,
+ [invocation.state.globals],
+ { parallel: true, maxSteps: 1_000_000 }
+ )
+ })
+ })
+ })
})
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
index 2e9330b588a3..70f7af772d2b 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-executor.ts
@@ -1,3 +1,4 @@
+import { LRUCache } from 'lru-cache'
import { DateTime } from 'luxon'
import { Counter, Histogram } from 'prom-client'
@@ -13,6 +14,7 @@ import {
RustExecResult,
isUnsupportedByRustVm,
loadHogvmNodeModule,
+ programKey,
} from './rust-vm'
import { RustVmBatchScheduler } from './rust-vm-batch-scheduler'
@@ -24,9 +26,10 @@ import { RustVmBatchScheduler } from './rust-vm-batch-scheduler'
* 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.
+ * (`executeRegisteredSync`); `executeBatched` enqueues into a {@link RustVmBatchScheduler} that
+ * coalesces same-program invocations into one `executeRegisteredBatch` FFI crossing per tick,
+ * executed off the JS event loop. Both execute a program the addon registered once per distinct
+ * bytecode, so the per-event cost is the globals crossing, not re-marshalling and re-decoding.
*/
export const rustVmExecution = new Counter({
@@ -41,17 +44,47 @@ export const rustVmExecutionDuration = new Histogram({
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 100],
})
+export const rustVmProgramRegistrations = new Counter({
+ name: 'hogvm_rust_program_registrations_total',
+ help: 'Programs registered with the Rust HogVM after a miss in the handle cache',
+})
+
+/** Bounds the Rust-side registry: one entry per distinct program, shared by every function with that bytecode. */
+export const MAX_REGISTERED_PROGRAMS = 500
+
+type RegistryBindings = Required<
+ Pick<HogvmNodeModule, 'registerProgram' | 'releaseProgram' | 'executeRegisteredSync' | 'executeRegisteredBatch'>
+>
+
export class RustVmExecutor {
private scheduler: RustVmBatchScheduler
+ /**
+ * Handles by bytecode content: every team has its own hog function row, so one template arrives
+ * as thousands of functions with identical bytecode and registers once. `dispose` is the single
+ * owner of releasing handles, so no caller releases directly and no handle is released twice.
+ */
+ private handles: LRUCache<string, number>
+
constructor(private options: { mmdbPath: string }) {
- this.scheduler = new RustVmBatchScheduler((program, events) => {
+ this.scheduler = new RustVmBatchScheduler(async (bytecode, 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'))
+ throw new Error('Rust HogVM native module unavailable')
+ }
+ const registry = this.registryOf(module_)
+ if (!registry) {
+ return module_.executeBatch(bytecode, events, { parallel: true, maxSteps: RUST_MAX_STEPS })
}
- return module_.executeBatch(program, events, { parallel: true, maxSteps: RUST_MAX_STEPS })
+ // Resolve the handle in the same synchronous span as the FFI call: `handleFor`
+ // re-registers an evicted program, and nothing can release the handle before the call.
+ const handle = this.handleFor(registry, bytecode)
+ return registry.executeRegisteredBatch(handle, events, { parallel: true, maxSteps: RUST_MAX_STEPS })
+ })
+ this.handles = new LRUCache({
+ max: MAX_REGISTERED_PROGRAMS,
+ dispose: (handle) => this.getModule()?.releaseProgram?.(handle),
})
}
@@ -59,6 +92,31 @@ export class RustVmExecutor {
return loadHogvmNodeModule({ mmdbPath: this.options.mmdbPath })
}
+ /**
+ * All four registry bindings, or null when the addon predates them: it is built and shipped
+ * separately from this code, and the caller then executes unregistered instead of throwing.
+ */
+ private registryOf(module_: HogvmNodeModule): RegistryBindings | null {
+ const { registerProgram, releaseProgram, executeRegisteredSync, executeRegisteredBatch } = module_
+ if (!registerProgram || !releaseProgram || !executeRegisteredSync || !executeRegisteredBatch) {
+ return null
+ }
+ return { registerProgram, releaseProgram, executeRegisteredSync, executeRegisteredBatch }
+ }
+
+ private handleFor(registry: RegistryBindings, bytecode: unknown[]): number {
+ const key = programKey(bytecode)
+ const cached = this.handles.get(key)
+ if (cached !== undefined) {
+ return cached
+ }
+
+ rustVmProgramRegistrations.inc()
+ const handle = registry.registerProgram(bytecode)
+ this.handles.set(key, handle)
+ return handle
+ }
+
/**
* Count and log a fallback so every node-vm handoff is attributable to a function. Returns
* null for the caller to pass through.
@@ -85,7 +143,7 @@ export class RustVmExecutor {
* Execute one transformation invocation on the Rust VM. Returns null when the Node VM must
* run it instead.
*
- * Runs through `executeSync` on the JS thread — the same threading model as the Node VM's
+ * Runs through `executeRegisteredSync` 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.
*/
@@ -103,9 +161,16 @@ export class RustVmExecutor {
let rust
try {
- rust = module_.executeSync(invocation.hogFunction.bytecode, invocation.state.globals, {
- maxSteps: RUST_MAX_STEPS,
- })
+ const registry = this.registryOf(module_)
+ rust = registry
+ ? registry.executeRegisteredSync(
+ this.handleFor(registry, invocation.hogFunction.bytecode),
+ invocation.state.globals,
+ { maxSteps: RUST_MAX_STEPS }
+ )
+ : module_.executeSync(invocation.hogFunction.bytecode, invocation.state.globals, {
+ maxSteps: RUST_MAX_STEPS,
+ })
} catch (error) {
// A throw here is the boundary or the native side, not the program's own error path —
// marshalling failures (e.g. globals containing NaN or Infinity, which serde_json
@@ -121,7 +186,7 @@ export class RustVmExecutor {
/**
* 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.
+ * in flight during the same tick share one `executeRegisteredBatch` 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.
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm.ts b/nodejs/src/cdp/hog-transformations/rust-vm.ts
index fcd3cdf3b7e9..f6d66e16e4a8 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm.ts
@@ -1,3 +1,5 @@
+import { createHash } from 'crypto'
+
import { logger } from '~/common/utils/logger'
import { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'
@@ -40,6 +42,22 @@ export function isUnsupportedByRustVm(error: string): boolean {
)
}
+const programKeys = new WeakMap<unknown[], string>()
+
+/**
+ * Content hash of a bytecode array, cached per instance (the hog function manager hands out one
+ * array per function). Every team has its own copy of a template, and keying by content is what
+ * lets those copies share a batch and a registration.
+ */
+export function programKey(bytecode: unknown[]): string {
+ let key = programKeys.get(bytecode)
+ if (key === undefined) {
+ key = createHash('sha256').update(JSON.stringify(bytecode)).digest('base64')
+ programKeys.set(bytecode, key)
+ }
+ return key
+}
+
export interface RustExecResult {
result?: unknown
error?: string
@@ -58,6 +76,19 @@ export interface HogvmNodeModule {
events: unknown[],
options?: { parallel?: boolean; maxSteps?: number }
): Promise<RustExecResult[]>
+ /**
+ * The registry bindings are optional: the addon is a separately built native binary, and a
+ * deployment can run one that predates them. Callers feature-check and fall back to the
+ * unregistered calls above instead of throwing on every invocation.
+ */
+ registerProgram?(program: unknown[]): number
+ releaseProgram?(handle: number): void
+ executeRegisteredSync?(handle: number, globals: unknown, options?: { maxSteps?: number }): RustExecResult
+ executeRegisteredBatch?(
+ handle: number,
+ events: unknown[],
+ options?: { parallel?: boolean; maxSteps?: number }
+ ): Promise<RustExecResult[]>
}
let cachedModule: HogvmNodeModule | null | undefined = undefined
diff --git a/rust/common/hogvm/node/index.d.ts b/rust/common/hogvm/node/index.d.ts
index bb6eafb083b9..7cffe5931f31 100644
--- a/rust/common/hogvm/node/index.d.ts
+++ b/rust/common/hogvm/node/index.d.ts
@@ -54,3 +54,34 @@ export function executeBatch(
events: unknown[],
options?: ExecuteBatchOptions
): Promise<HogExecResult[]>
+
+/**
+ * Validate and token-decode a program once, returning a handle for `executeRegisteredSync`, so a
+ * program executed repeatedly isn't re-marshalled and re-decoded per call. Invalid bytecode still
+ * gets a handle — executions through it report the validation error.
+ */
+export function registerProgram(program: unknown[]): number
+
+/**
+ * Drop a registered program and free its slot for reuse. Releasing an unknown or already-released
+ * handle is a no-op. A handle must not be executed after it is released.
+ */
+export function releaseProgram(handle: number): void
+
+/** `executeSync` against a program registered with `registerProgram`. */
+export function executeRegisteredSync(
+ handle: number,
+ globals: unknown,
+ options?: ExecuteSyncOptions
+): HogExecResult
+
+/**
+ * `executeBatch` against a program registered with `registerProgram`: one napi crossing for many
+ * events, off the JS event loop, with no per-batch bytecode marshal or decode. Same per-event
+ * `marshal_error:` salvage as `executeBatch`.
+ */
+export function executeRegisteredBatch(
+ handle: number,
+ 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 90f8e0d8ece5..f2cc4c8af3f2 100644
--- a/rust/common/hogvm/node/src/exec.rs
+++ b/rust/common/hogvm/node/src/exec.rs
@@ -64,6 +64,29 @@ pub fn run_batch_salvaged(
events: Vec<Result<Value, String>>,
parallel: bool,
max_steps: Option<usize>,
+) -> Vec<HogExecResult> {
+ salvage(events, |ok_events| {
+ run_batch(tokens, ok_events, parallel, max_steps)
+ })
+}
+
+/// Like [`run_batch_salvaged`], but from a program built once by [`build_program`]. A program that
+/// failed to build errors every converted event, and marshal errors keep their own prefix.
+pub fn run_batch_program_salvaged(
+ program: &Result<Program, String>,
+ events: Vec<Result<Value, String>>,
+ parallel: bool,
+ max_steps: Option<usize>,
+) -> Vec<HogExecResult> {
+ salvage(events, |ok_events| match program {
+ Ok(program) => run_batch_program(program, ok_events, parallel, max_steps),
+ Err(e) => ok_events.iter().map(|_| error_result(e, 0.0)).collect(),
+ })
+}
+
+fn salvage(
+ events: Vec<Result<Value, String>>,
+ run: impl FnOnce(&[Value]) -> Vec<HogExecResult>,
) -> Vec<HogExecResult> {
let mut ok_events = Vec::with_capacity(events.len());
let mut slots: Vec<Option<String>> = Vec::with_capacity(events.len());
@@ -77,14 +100,12 @@ pub fn run_batch_salvaged(
}
}
- let mut executed = run_batch(tokens, &ok_events, parallel, max_steps).into_iter();
+ let mut executed = run(&ok_events).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"),
+ None => executed.next().expect("one result per executed event"),
})
.collect()
}
@@ -158,7 +179,7 @@ fn run_chunk(program: &Program, chunk: &[Value], max_steps: Option<usize>) -> Ve
.collect()
}
-fn error_result(error: &str, duration_us: f64) -> HogExecResult {
+pub(crate) fn error_result(error: &str, duration_us: f64) -> HogExecResult {
HogExecResult {
result: None,
error: Some(error.to_string()),
@@ -298,6 +319,22 @@ mod tests {
assert_eq!(results[2].result, Some(json!("b")));
}
+ #[test]
+ fn salvaged_batch_keeps_marshal_errors_when_the_program_is_invalid() {
+ let program = build_program(vec![json!("not bytecode")]);
+ let events = vec![Err("nan in globals".to_string()), Ok(json!({}))];
+ let results = run_batch_program_salvaged(&program, events, false, None);
+ assert_eq!(
+ results[0].error.as_deref(),
+ Some("marshal_error:nan in globals")
+ );
+ assert!(results[1]
+ .error
+ .as_deref()
+ .unwrap()
+ .starts_with("invalid program"));
+ }
+
#[test]
fn salvaged_batch_with_all_marshal_errors_executes_nothing() {
let events = vec![Err("x".to_string()), Err("y".to_string())];
diff --git a/rust/common/hogvm/node/src/lib.rs b/rust/common/hogvm/node/src/lib.rs
index fb5e5deb2863..ea9b8c44a8b3 100644
--- a/rust/common/hogvm/node/src/lib.rs
+++ b/rust/common/hogvm/node/src/lib.rs
@@ -34,8 +34,8 @@ use napi_derive::napi;
use serde_json::Value;
pub use exec::{
- build_program, run_batch, run_batch_program, run_batch_salvaged, HogExecResult,
- MARSHAL_ERROR_PREFIX,
+ build_program, run_batch, run_batch_program, run_batch_program_salvaged, run_batch_salvaged,
+ HogExecResult, MARSHAL_ERROR_PREFIX,
};
#[napi(object)]
@@ -160,3 +160,208 @@ pub fn execute_sync(
.next()
.expect("run_batch returns one result per event")
}
+
+// Programs registered by `registerProgram` are validated and token-decoded once and executed by
+// handle, so the per-event cost is the globals crossing. Released slots are reused so the registry
+// stays bounded. Callers own the handle lifecycle: executing a released handle is a caller bug. It
+// errors as unknown, or runs the newer program once the slot is reused.
+#[derive(Default)]
+struct ProgramRegistry {
+ slots: Vec<Option<Result<hogvm::Program, String>>>,
+ free: Vec<u32>,
+}
+
+static REGISTERED_PROGRAMS: std::sync::RwLock<ProgramRegistry> =
+ std::sync::RwLock::new(ProgramRegistry {
+ slots: Vec::new(),
+ free: Vec::new(),
+ });
+
+/// Invalid bytecode still gets a handle, and executions through it report the validation error.
+#[napi]
+pub fn register_program(program: Value) -> u32 {
+ let tokens = match program {
+ Value::Array(tokens) => tokens,
+ _ => Vec::new(),
+ };
+ let built = exec::build_program(tokens);
+ let mut registry = REGISTERED_PROGRAMS.write().expect("registry poisoned");
+ if let Some(handle) = registry.free.pop() {
+ registry.slots[handle as usize] = Some(built);
+ return handle;
+ }
+ registry.slots.push(Some(built));
+ (registry.slots.len() - 1) as u32
+}
+
+/// Releasing an unknown or already-released handle is a no-op, so a double release cannot push the
+/// same slot onto the free list twice.
+#[napi]
+pub fn release_program(handle: u32) {
+ let mut registry = REGISTERED_PROGRAMS.write().expect("registry poisoned");
+ let Some(slot) = registry.slots.get_mut(handle as usize) else {
+ return;
+ };
+ if slot.take().is_some() {
+ registry.free.push(handle);
+ }
+}
+
+// A registered Program clone is two Arc bumps; cloning out keeps the lock scope minimal.
+fn get_registered(handle: u32) -> Result<hogvm::Program, String> {
+ REGISTERED_PROGRAMS
+ .read()
+ .expect("registry poisoned")
+ .slots
+ .get(handle as usize)
+ .cloned()
+ .flatten()
+ .unwrap_or_else(|| Err(format!("unknown program handle {handle}")))
+}
+
+#[napi]
+pub fn execute_registered_sync(
+ handle: u32,
+ globals: Value,
+ options: Option<ExecuteSyncOptions>,
+) -> HogExecResult {
+ let max_steps = options.and_then(|o| o.max_steps).map(|m| m as usize);
+ match get_registered(handle) {
+ Ok(program) => {
+ exec::run_batch_program(&program, std::slice::from_ref(&globals), false, max_steps)
+ .into_iter()
+ .next()
+ .expect("one result per event")
+ }
+ Err(e) => exec::error_result(&e, 0.0),
+ }
+}
+
+#[cfg(not(feature = "noop"))]
+pub struct ExecuteRegisteredBatchTask {
+ program: Result<hogvm::Program, String>,
+ events: Vec<Result<Value, String>>,
+ parallel: bool,
+ max_steps: Option<usize>,
+}
+
+#[cfg(not(feature = "noop"))]
+impl Task for ExecuteRegisteredBatchTask {
+ type Output = Vec<HogExecResult>;
+ type JsValue = Vec<HogExecResult>;
+
+ fn compute(&mut self) -> NapiResult<Self::Output> {
+ let events = std::mem::take(&mut self.events);
+ Ok(exec::run_batch_program_salvaged(
+ &self.program,
+ events,
+ self.parallel,
+ self.max_steps,
+ ))
+ }
+
+ fn resolve(&mut self, _env: Env, output: Self::Output) -> NapiResult<Self::JsValue> {
+ Ok(output)
+ }
+}
+
+#[cfg(not(feature = "noop"))]
+#[napi(ts_return_type = "Promise<Array<HogExecResult>>")]
+pub fn execute_registered_batch(
+ env: Env,
+ handle: u32,
+ events: Vec<JsUnknown>,
+ options: Option<ExecuteBatchOptions>,
+) -> AsyncTask<ExecuteRegisteredBatchTask> {
+ // Clone the program out on the JS thread so the task owns it: an eviction that releases the
+ // handle after this call cannot pull the program out from under the running batch.
+ let program = get_registered(handle);
+ 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(ExecuteRegisteredBatchTask {
+ program,
+ events,
+ parallel,
+ max_steps,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ // The registry is process-global, so these tests must not run concurrently with each other:
+ // they assert on which slot a registration lands in, and cargo runs tests in parallel threads.
+ static REGISTRY_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ fn registry_guard() -> std::sync::MutexGuard<'static, ()> {
+ // A panicking test poisons the lock; the registry itself stays consistent, so recover
+ // rather than cascading a failure into every other test in this module.
+ REGISTRY_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ // "_H" header, version 1, push int 1, RETURN
+ fn program(value: i64) -> Value {
+ json!(["_H", 1, 33, value, 38])
+ }
+
+ #[test]
+ fn released_handles_are_reused_so_the_registry_stays_bounded() {
+ let _guard = registry_guard();
+ let first = register_program(program(1));
+ release_program(first);
+ let second = register_program(program(2));
+ assert_eq!(first, second);
+
+ let result = execute_registered_sync(second, json!({}), None);
+ assert_eq!(result.error, None);
+ assert_eq!(result.result, Some(json!(2)));
+ }
+
+ #[test]
+ fn executing_a_released_handle_errors_instead_of_running_a_stale_program() {
+ let _guard = registry_guard();
+ let handle = register_program(program(1));
+ release_program(handle);
+
+ let result = execute_registered_sync(handle, json!({}), None);
+ assert!(result.result.is_none());
+ assert!(result
+ .error
+ .as_deref()
+ .unwrap()
+ .contains("unknown program handle"));
+ }
+
+ #[test]
+ fn releasing_twice_does_not_hand_the_same_slot_out_to_two_registrations() {
+ let _guard = registry_guard();
+ let handle = register_program(program(1));
+ release_program(handle);
+ release_program(handle);
+
+ let a = register_program(program(1));
+ let b = register_program(program(2));
+ assert_ne!(a, b);
+
+ assert_eq!(
+ execute_registered_sync(a, json!({}), None).result,
+ Some(json!(1))
+ );
+ assert_eq!(
+ execute_registered_sync(b, json!({}), None).result,
+ Some(json!(2))
+ );
+ }
+}