: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): shadow-execute transformations on the rust hogvm (#67901)
José Sequeira526560c856f1
diff --git a/.github/workflows/ci-nodejs-container.yml b/.github/workflows/ci-nodejs-container.ymlindex 40f624b851c9..b158d2c47072 100644--- a/.github/workflows/ci-nodejs-container.yml+++ b/.github/workflows/ci-nodejs-container.yml@@ -46,6 +46,7 @@ jobs:- 'common/replay-shared/**'- 'common/replay-headless/**'- 'rust/cyclotron-node/**'+ - 'rust/common/hogvm/**'- 'Dockerfile.node'- '.github/workflows/ci-nodejs-container.yml'- 'turbo.json'diff --git a/Dockerfile.node b/Dockerfile.nodeindex c356dc78beda..a182e946e05a 100644--- a/Dockerfile.node+++ b/Dockerfile.node@@ -73,6 +73,8 @@ COPY ./common/replay-headless/build.mjs ./common/replay-headless/# Build cyclotron firstRUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/cyclotron build+# Build the rust hogvm napi addon (shadow execution of transformations)+RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/hogvm-node build# Build replay-headless (dependency of nodejs rasterizer code)RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/replay-headless build@@ -128,6 +130,9 @@ RUN echo ${COMMIT_HASH:-unknown} > /code/commit.txtCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/dist /code/rust/cyclotron-node/distCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/package.json /code/rust/cyclotron-node/package.jsonCOPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/index.node /code/rust/cyclotron-node/index.node+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/package.json /code/rust/common/hogvm/node/package.json+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.js /code/rust/common/hogvm/node/index.js+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.node /code/rust/common/hogvm/node/index.nodeCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/dist /code/common/plugin_transpiler/distCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/node_modules /code/common/plugin_transpiler/node_modulesCOPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/package.json /code/common/plugin_transpiler/package.jsondiff --git a/nodejs/package.json b/nodejs/package.jsonindex 60ba5bf7da5c..eb00ff6802f4 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -46,6 +46,8 @@"services": "pnpm services:stop && pnpm services:clean && pnpm services:start","build:cyclotron": "pnpm --filter=@posthog/cyclotron package","build:cyclotron:dev": "pnpm --filter=@posthog/cyclotron run build:dev",+ "build:hogvm-node": "pnpm --filter=@posthog/hogvm-node build",+ "build:hogvm-node:dev": "pnpm --filter=@posthog/hogvm-node run build:dev","generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/types .","update-ai-costs": "ts-node src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts","sync-segment-icons": "DATABASE_URL=something ts-node src/cdp/segment/sync-segment-icons.ts",@@ -87,6 +89,7 @@"@opentelemetry/semantic-conventions": "^1.36.0","@posthog/cyclotron": "workspace:*","@posthog/hogvm": "workspace:*",+ "@posthog/hogvm-node": "workspace:*","@posthog/replay-headless": "workspace:*","@posthog/siphash": "1.1.1","@pyroscope/nodejs": "^0.4.8",diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex 4d6e93fb5a80..7e8b6226f3dc 100644--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts@@ -30,11 +30,14 @@ import { EncryptedFields } from '../utils/encryption-utils'import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'import { createInvocation } from '../utils/invocation-utils'import { mirrorCall } from '../utils/mirror-call'+import { RustVmShadow } from './rust-vm-shadow'import { getTransformationFunctions } from './transformation-functions'export interface HogTransformerConfig {siteUrl: stringhogWatcherSampleRate: number+ hogRustVmShadowSampleRate: number+ mmdbFileLocation: string}export const hogTransformationDroppedEvents = new Counter({@@ -85,6 +88,7 @@ export class HogTransformerService implements HogTransformer {private invocationResults: CyclotronJobInvocationResult[] = []private cachedGeoIp?: GeoIpprivate cachedTransformationFunctions?: ReturnType<typeof getTransformationFunctions>+ private rustVmShadow: RustVmShadowconstructor(private hogFunctionManager: HogFunctionManagerService,@@ -96,7 +100,12 @@ export class HogTransformerService implements HogTransformer {private geoipService: GeoIPService,private redis: RedisV2,private config: HogTransformerConfig- ) {}+ ) {+ this.rustVmShadow = new RustVmShadow({+ sampleRate: config.hogRustVmShadowSampleRate,+ mmdbPath: config.mmdbFileLocation,+ })+ }public async start(): Promise<void> {}@@ -128,6 +137,8 @@ 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),])}@@ -399,12 +410,36 @@ export class HogTransformerService implements HogTransformer {const invocation = createInvocation(globalsWithInputs, hogFunction)- const result = isLegacyPluginHogFunction(hogFunction)- ? await this.pluginExecutor.execute(invocation)- : await this.hogExecutor.execute(invocation, {- functions: transformationFunctions,- asyncFunctionsNames: [],- })+ if (isLegacyPluginHogFunction(hogFunction)) {+ return await this.pluginExecutor.execute(invocation)+ }++ // 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, {+ 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}@@ -450,9 +485,10 @@ export class HogTransformerService implements HogTransformer {/*** Config needed by the HogTransformer when running inside ingestion.* This is CdpCoreServicesConfig (CDP redis, watcher, monitoring, encryption, etc.)- * plus the ingestion-specific CDP_HOG_WATCHER_SAMPLE_RATE from CommonConfig.+ * plus the ingestion-specific sample rates from CommonConfig.*/-export type HogTransformerServiceConfig = CdpCoreServicesConfig & Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE'>+export type HogTransformerServiceConfig = CdpCoreServicesConfig &+ Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE' | 'CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE' | 'MMDB_FILE_LOCATION'>export interface HogTransformerServiceDeps {geoipService: GeoIPService@@ -556,6 +592,8 @@ export function createHogTransformerService({siteUrl: config.SITE_URL,hogWatcherSampleRate: config.CDP_HOG_WATCHER_SAMPLE_RATE,+ hogRustVmShadowSampleRate: config.CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE,+ mmdbFileLocation: config.MMDB_FILE_LOCATION,})}diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.tsnew file mode 100644index 000000000000..b6edfa265737--- /dev/null+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts@@ -0,0 +1,196 @@+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 Global 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('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.tsnew file mode 100644index 000000000000..259a829268c8--- /dev/null+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts@@ -0,0 +1,258 @@+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 { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'++/**+ * 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.+ */++// The Rust VM budgets steps, not wall-clock time; generous so it never trips before the Node VM's+// timeout would.+const RUST_MAX_STEPS = 1_000_000+// 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'+ | '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+}++interface RustExecResult {+ result?: unknown+ error?: string+ durationUs: number+}++interface HogvmNodeModule {+ init(options: { mmdbPath?: string; knownBotUaList?: string[]; knownBotIpList?: string[] }): void+ executeBatch(+ program: unknown[],+ events: unknown[],+ options?: { parallel?: boolean; maxSteps?: number }+ ): Promise<RustExecResult[]>+}++export function classifyShadowOutcome(node: ShadowNodeResult, rust: RustExecResult | undefined): ShadowOutcome {+ if (!rust) {+ return 'rust_error'+ }+ if (rust.error) {+ // Host functions the rust binding doesn't implement — not comparable, not a divergence.+ // 'Unknown Global <name>' is the rust VM's exact error for calling a function it doesn't+ // know; anchored to the prefix so other errors mentioning the words can't be swallowed.+ if (rust.error.includes('unsupported_ext_fn:') || rust.error.startsWith('Unknown Global ')) {+ 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++ 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.buffer.length >= MAX_BUFFER_SIZE) {+ shadowComparison.inc({ outcome: 'dropped' })+ return+ }+ this.buffer.push(item)+ }++ /**+ * 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+ }+ try {+ const module_: HogvmNodeModule = require('@posthog/hogvm-node')+ module_.init({+ mmdbPath: this.options.mmdbPath,+ knownBotUaList: KNOWN_BOT_UA_LIST,+ knownBotIpList: KNOWN_BOT_IP_LIST,+ })+ this.module_ = module_+ logger.info('🦀', 'Rust HogVM shadow mode enabled', { sampleRate: this.options.sampleRate })+ } catch (error) {+ this.module_ = null+ logger.warn('🦀', 'Rust HogVM native module unavailable, shadow mode disabled', {+ error: String(error),+ })+ }+ return this.module_+ }+}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex c8998bcdda73..39ac96bc5d6d 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -186,6 +186,10 @@ 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+// Event loop yield helper (yieldEventLoopIfNeeded)EVENT_LOOP_YIELD_THRESHOLD_MS: number}@@ -356,6 +360,7 @@ export function getDefaultCommonConfig(): CommonConfig {// Shared between ingestion and CDPCDP_HOG_WATCHER_SAMPLE_RATE: 0,+ CDP_HOG_RUST_VM_SHADOW_SAMPLE_RATE: 0,// Event loop yield helperEVENT_LOOP_YIELD_THRESHOLD_MS: 200,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 02874c0f86fe..4cc982c9d839 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1481,6 +1481,9 @@ importers:'@posthog/hogvm':specifier: workspace:*version: link:../common/hogvm/typescript+ '@posthog/hogvm-node':+ specifier: workspace:*+ version: link:../rust/common/hogvm/node'@posthog/replay-headless':specifier: workspace:*version: link:../common/replay-headless@@ -4388,6 +4391,8 @@ importers:specifier: 'catalog:'version: 0.2.4([email protected]([email protected]))+ rust/common/hogvm/node: {}+rust/cyclotron-node:devDependencies:'@types/node':diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 43c4ae3821a5..6165aeb61d1e 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -25,6 +25,7 @@ packages:- tools/*- '!tools/hedgebox-dummy'- rust/cyclotron-node+ - rust/common/hogvm/nodeblockExoticSubdeps: truetrustPolicy: no-downgradediff --git a/rust/common/hogvm/node/.gitignore b/rust/common/hogvm/node/.gitignorenew file mode 100644index 000000000000..89fb9af0a25e--- /dev/null+++ b/rust/common/hogvm/node/.gitignore@@ -0,0 +1,2 @@+target/+*.nodediff --git a/rust/common/hogvm/node/Cargo.lock b/rust/common/hogvm/node/Cargo.locknew file mode 100644index 000000000000..bfc9eda97c87--- /dev/null+++ b/rust/common/hogvm/node/Cargo.lock@@ -0,0 +1,997 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "cc"+version = "1.2.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "js-sys",+ "num-traits",+ "serde",+ "wasm-bindgen",+ "windows-link",+]++[[package]]+name = "chrono-tz"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"+dependencies = [+ "chrono",+ "phf",+]++[[package]]+name = "convert_case"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"+dependencies = [+ "unicode-segmentation",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+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"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "ctor"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+ "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"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "wasip2",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest",+]++[[package]]+name = "hogvm"+version = "0.1.0"+dependencies = [+ "base64",+ "chrono",+ "chrono-tz",+ "hmac",+ "indexmap",+ "md-5",+ "once_cell",+ "quick_cache",+ "rand",+ "regex",+ "serde",+ "serde_json",+ "sha2",+ "thiserror",+]++[[package]]+name = "hogvm-node"+version = "0.1.0"+dependencies = [+ "hogvm",+ "maxminddb",+ "napi",+ "napi-build",+ "napi-derive",+ "rayon",+ "serde_json",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+]++[[package]]+name = "ipnetwork"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf466541e9d546596ee94f9f69590f89473455f88372423e0008fc1a7daf100e"+dependencies = [+ "serde",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "maxminddb"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6087e5d8ea14861bb7c7f573afbc7be3798d3ef0fae87ec4fd9a4de9a127c3c"+dependencies = [+ "ipnetwork",+ "log",+ "memchr",+ "serde",+]++[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest",+]++[[package]]+name = "memchr"+version = "2.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"++[[package]]+name = "napi"+version = "2.16.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"+dependencies = [+ "bitflags",+ "ctor",+ "napi-derive",+ "napi-sys",+ "once_cell",+ "serde",+ "serde_json",+]++[[package]]+name = "napi-build"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9c366d2c8c60b86fa632df75f745509b52f9128f91a6bad4c796e44abb505e1"++[[package]]+name = "napi-derive"+version = "2.16.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"+dependencies = [+ "cfg-if",+ "convert_case",+ "napi-derive-backend",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "napi-derive-backend"+version = "1.0.75"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"+dependencies = [+ "convert_case",+ "once_cell",+ "proc-macro2",+ "quote",+ "regex",+ "semver",+ "syn",+]++[[package]]+name = "napi-sys"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"+dependencies = [+ "libloading",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "phf"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"+dependencies = [+ "phf_shared",+]++[[package]]+name = "phf_shared"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"+dependencies = [+ "siphasher",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quick_cache"+version = "0.6.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9c6658afe513a3b484e3abfdaa0d03ef3c0bbf017542c178dd55f94eb3051f9"+dependencies = [+ "ahash",+ "equivalent",+ "hashbrown 0.16.1",+ "parking_lot",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "rand"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"+dependencies = [+ "libc",+ "rand_chacha",+ "rand_core",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+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"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "regex"+version = "1.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "rustversion"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.150"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "siphasher"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "zerocopy"+version = "0.8.52"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.52"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zmij"+version = "1.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"diff --git a/rust/common/hogvm/node/Cargo.toml b/rust/common/hogvm/node/Cargo.tomlnew file mode 100644index 000000000000..cb501de8ed23--- /dev/null+++ b/rust/common/hogvm/node/Cargo.toml@@ -0,0 +1,31 @@+# napi-rs binding exposing the Rust HogVM to Node for shadow execution of ingestion+# transformations. Its own [workspace] table keeps it out of the parent rust/ workspace build;+# build it via the package.json scripts (`pnpm build`) or `cargo build --release` here.+[workspace]++[package]+name = "hogvm-node"+version = "0.1.0"+edition = "2021"+publish = false++[lib]+crate-type = ["cdylib", "lib"]++[features]+# Makes the napi macros no-ops so `cargo test --features noop` links without a Node host.+noop = ["napi/noop", "napi-derive/noop"]++[dependencies]+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]+napi-build = "2"++[profile.release]+lto = truediff --git a/rust/common/hogvm/node/build.rs b/rust/common/hogvm/node/build.rsnew file mode 100644index 000000000000..0f1b01002b07--- /dev/null+++ b/rust/common/hogvm/node/build.rs@@ -0,0 +1,3 @@+fn main() {+ napi_build::setup();+}diff --git a/rust/common/hogvm/node/index.d.ts b/rust/common/hogvm/node/index.d.tsnew file mode 100644index 000000000000..a0a2bc83d498--- /dev/null+++ b/rust/common/hogvm/node/index.d.ts@@ -0,0 +1,38 @@+export interface InitOptions {+ /** Path to a GeoLite2/GeoIP2 City mmdb file, enables the geoipLookup host function. */+ mmdbPath?: string+ /** Lowercased substrings matched against user agents by isKnownBotUserAgent. */+ knownBotUaList?: string[]+ /** Exact IPs matched by isKnownBotIp. */+ knownBotIpList?: string[]+}++export interface HogExecResult {+ /** The program's return value; null/undefined when the execution errored. */+ result?: unknown+ error?: string+ durationUs: 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.+ */+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[]>diff --git a/rust/common/hogvm/node/index.js b/rust/common/hogvm/node/index.jsnew file mode 100644index 000000000000..395b8c28b945--- /dev/null+++ b/rust/common/hogvm/node/index.js@@ -0,0 +1 @@+module.exports = require('./index.node')diff --git a/rust/common/hogvm/node/package.json b/rust/common/hogvm/node/package.jsonnew file mode 100644index 000000000000..eafdeee5e248--- /dev/null+++ b/rust/common/hogvm/node/package.json@@ -0,0 +1,22 @@+{+ "name": "@posthog/hogvm-node",+ "version": "0.1.0",+ "private": true,+ "description": "Rust HogVM exposed to Node via napi-rs, for shadow execution of ingestion transformations",+ "main": "index.js",+ "types": "index.d.ts",+ "scripts": {+ "test": "cargo test --features noop",+ "build": "cargo build --release && pnpm run build:move-lib",+ "build:dev": "cargo build && pnpm run build:move-lib:dev",+ "build:move-lib": "TARGET_DIR=${CARGO_TARGET_DIR:-target} && cp \"$TARGET_DIR/release/libhogvm_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/release/libhogvm_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/release/\" && exit 1)",+ "build:move-lib:dev": "TARGET_DIR=${CARGO_TARGET_DIR:-target} && cp \"$TARGET_DIR/debug/libhogvm_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/debug/libhogvm_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/debug/\" && exit 1)",+ "clean": "rm -rf index.node"+ },+ "license": "MIT",+ "files": [+ "index.js",+ "index.d.ts",+ "index.node"+ ]+}diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rsnew file mode 100644index 000000000000..449469606841--- /dev/null+++ b/rust/common/hogvm/node/src/exec.rs@@ -0,0 +1,326 @@+//! Batch execution of one Hog program against many event-globals.++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;++const PARALLEL_CHUNK_SIZE: usize = 500;++#[napi(object)]+pub struct HogExecResult {+ /// The program's return value; None when the execution errored.+ pub result: Option<Value>,+ pub error: Option<String>,+ pub duration_us: f64,+}++pub fn run_batch(+ tokens: &[Value],+ events: &[Value],+ parallel: bool,+ max_steps: Option<usize>,+) -> Vec<HogExecResult> {+ if tokens.is_empty() {+ return events+ .iter()+ .map(|_| error_result("invalid program: bytecode must be a non-empty array", 0.0))+ .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 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,+ Err(e) => {+ return chunk+ .iter()+ .map(|_| error_result(&format!("invalid program: {e}"), 0.0))+ .collect();+ }+ };++ let mut ctx = ExecutionContext::with_defaults(program).with_ext_fns(transformation_ext_fns());+ if let Some(max_steps) = max_steps {+ ctx.max_steps = max_steps;+ }++ chunk+ .iter()+ .map(|event| {+ ctx.set_globals(event.clone());+ let start = Instant::now();+ let outcome = sync_execute(&ctx, false);+ let duration_us = start.elapsed().as_secs_f64() * 1_000_000.0;+ match outcome {+ Ok(value) => HogExecResult {+ result: Some(value),+ error: None,+ duration_us,+ },+ Err(failure) => error_result(&failure.error.to_string(), duration_us),+ }+ })+ .collect()+}++fn error_result(error: &str, duration_us: f64) -> HogExecResult {+ HogExecResult {+ result: None,+ error: Some(error.to_string()),+ duration_us,+ }+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::*;+ use crate::ext_fns::set_bot_lists_for_tests;++ // "_H" header, version 1, push int 1, push int 2, PLUS, RETURN+ fn add_program() -> Vec<Value> {+ vec![+ json!("_H"),+ json!(1),+ json!(33),+ json!(1),+ json!(33),+ json!(2),+ json!(6),+ json!(38),+ ]+ }++ // push "name", GET_GLOBAL (1 chain part), RETURN — returns globals.name+ fn get_global_program(name: &str) -> Vec<Value> {+ vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!(name),+ json!(1),+ json!(1),+ json!(38),+ ]+ }++ // push arg (a string), CALL_GLOBAL fn with 1 arg, RETURN+ fn call_fn_program(fn_name: &str, arg: &str) -> Vec<Value> {+ vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!(arg),+ json!(2),+ json!(fn_name),+ json!(1),+ json!(38),+ ]+ }++ #[test]+ fn executes_each_event_with_its_own_globals_in_order() {+ 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);+ }+ }+ }++ #[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);+ assert_eq!(results[0].result, Some(json!("ok")));+ assert!(results[1].result.is_none());+ assert!(results[1].error.as_deref().unwrap().contains("name"));+ }++ #[test]+ fn invalid_program_errors_every_event() {+ 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"));+ }+ }++ #[test]+ fn empty_program_errors_every_event() {+ let results = run_batch(&[], &[json!({})], false, None);+ assert!(results[0].error.is_some());+ }++ #[test]+ fn max_steps_budget_is_enforced() {+ let results = run_batch(&add_program(), &[json!({})], false, Some(1));+ assert!(results[0].error.is_some());+ 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!({})],+ false,+ None,+ );+ assert!(results[0]+ .error+ .as_deref()+ .unwrap()+ .contains("posthogCapture is not supported in transformations"));+ }++ #[test]+ fn unsupported_ext_fns_are_classifiable() {+ let results = run_batch(+ &call_fn_program("generateMessagingPreferencesUrl", "x"),+ &[json!({})],+ false,+ None,+ );+ assert!(results[0]+ .error+ .as_deref()+ .unwrap()+ .contains("unsupported_ext_fn:generateMessagingPreferencesUrl"));+ }++ #[test]+ fn geoip_lookup_without_init_is_classified_unsupported() {+ // GEOIP is never initialized in the test process.+ let results = run_batch(+ &call_fn_program("geoipLookup", "89.160.20.129"),+ &[json!({})],+ false,+ None,+ );+ assert!(results[0]+ .error+ .as_deref()+ .unwrap()+ .contains("unsupported_ext_fn:geoipLookup"));+ }++ #[test]+ fn print_is_a_noop_and_execution_continues() {+ // print("x") (POP the call result), then return 1+2+ let mut program = vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!("x"),+ json!(2),+ json!("print"),+ json!(1),+ json!(35),+ ];+ program.extend(add_program().into_iter().skip(2));+ let results = run_batch(&program, &[json!({})], false, None);+ assert_eq!(results[0].error, None);+ assert_eq!(results[0].result, Some(json!(3)));+ }++ #[test]+ fn known_bot_user_agent_matches_lowercased_substring() {+ set_bot_lists_for_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)));+ }++ #[test]+ fn known_bot_ip_matches_exactly() {+ set_bot_lists_for_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)));+ }++ #[test]+ fn clean_null_values_via_the_vm_strips_nulls_from_globals() {+ let results = run_batch(+ &call_fn_program("cleanNullValues", "unused"),+ &[json!({})],+ false,+ None,+ );+ // A string arg passes through untouched.+ assert_eq!(results[0].result, Some(json!("unused")));++ // cleanNullValues(globals.g)+ let program = vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!("g"),+ json!(1),+ json!(1),+ json!(2),+ json!("cleanNullValues"),+ json!(1),+ json!(38),+ ];+ 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/ext_fns.rs b/rust/common/hogvm/node/src/ext_fns.rsnew file mode 100644index 000000000000..88d926cb8abf--- /dev/null+++ b/rust/common/hogvm/node/src/ext_fns.rs@@ -0,0 +1,185 @@+//! The host functions the Node executor exposes to transformations, mirrored from+//! `nodejs/src/cdp/hog-transformations/transformation-functions.ts` (plus `print`, which the Node+//! VM surfaces as logs we don't compare).++use std::collections::HashMap;+use std::sync::OnceLock;++use hogvm::{construct_free_standing, native_func, HogLiteral, NativeFunction, VmError};+use serde_json::Value;++use crate::geoip;++static BOT_UA_LIST: OnceLock<Vec<String>> = OnceLock::new();+static BOT_IP_LIST: OnceLock<Vec<String>> = OnceLock::new();++// Mirrors MAX_DEPTH in transformation-functions.ts.+const CLEAN_NULL_VALUES_MAX_DEPTH: usize = 3;++/// Set once at `init`; later calls are ignored.+pub fn set_bot_lists(ua_list: Option<Vec<String>>, ip_list: Option<Vec<String>>) {+ if let Some(list) = ua_list {+ let _ = BOT_UA_LIST.set(list);+ }+ if let Some(list) = ip_list {+ let _ = BOT_IP_LIST.set(list);+ }+}++#[cfg(test)]+pub fn set_bot_lists_for_tests() {+ set_bot_lists(+ Some(vec!["googlebot".to_string()]),+ Some(vec!["1.2.3.4".to_string()]),+ );+}++pub fn unsupported(name: &str) -> VmError {+ VmError::NativeCallFailed(format!("unsupported_ext_fn:{name}"))+}++pub fn transformation_ext_fns() -> HashMap<String, NativeFunction> {+ static EXT_FNS: OnceLock<HashMap<String, NativeFunction>> = OnceLock::new();+ EXT_FNS+ .get_or_init(|| {+ let mut fns: HashMap<String, NativeFunction> = HashMap::new();++ fns.insert(+ "print".to_string(),+ native_func(|_vm, _args| Ok(HogLiteral::Null.into())),+ );++ fns.insert(+ "geoipLookup".to_string(),+ native_func(|vm, args| {+ if !geoip::is_initialized() {+ return Err(unsupported("geoipLookup"));+ }+ let Some(arg) = args.first() else {+ return Ok(HogLiteral::Null.into());+ };+ let HogLiteral::String(ip) = arg.deref(&vm.heap)? else {+ return Ok(HogLiteral::Null.into());+ };+ match geoip::lookup(ip) {+ Some(city) => construct_free_standing(city, 0),+ None => Ok(HogLiteral::Null.into()),+ }+ }),+ );++ fns.insert(+ "cleanNullValues".to_string(),+ native_func(|vm, args| {+ let Some(arg) = args.first() else {+ return Ok(HogLiteral::Null.into());+ };+ let value = vm.hog_to_json(arg)?;+ construct_free_standing(clean_null_values(value, 1), 0)+ }),+ );++ fns.insert(+ "isKnownBotUserAgent".to_string(),+ native_func(|vm, args| {+ let Some(list) = BOT_UA_LIST.get() else {+ return Err(unsupported("isKnownBotUserAgent"));+ };+ let Some(arg) = args.first() else {+ return Ok(HogLiteral::Boolean(false).into());+ };+ let HogLiteral::String(ua) = arg.deref(&vm.heap)? else {+ return Ok(HogLiteral::Boolean(false).into());+ };+ let ua = ua.to_lowercase();+ let known = list.iter().any(|bot| ua.contains(bot.as_str()));+ Ok(HogLiteral::Boolean(known).into())+ }),+ );++ fns.insert(+ "isKnownBotIp".to_string(),+ native_func(|vm, args| {+ let Some(list) = BOT_IP_LIST.get() else {+ return Err(unsupported("isKnownBotIp"));+ };+ let Some(arg) = args.first() else {+ return Ok(HogLiteral::Boolean(false).into());+ };+ let HogLiteral::String(ip) = arg.deref(&vm.heap)? else {+ return Ok(HogLiteral::Boolean(false).into());+ };+ let known = list.iter().any(|known_ip| known_ip == ip);+ Ok(HogLiteral::Boolean(known).into())+ }),+ );++ // Matches the Node executor: transformations may reference it, calling it throws.+ fns.insert(+ "postHogCapture".to_string(),+ native_func(|_vm, _args| {+ Err(VmError::NativeCallFailed(+ "posthogCapture is not supported in transformations".to_string(),+ ))+ }),+ );++ fns.insert(+ "generateMessagingPreferencesUrl".to_string(),+ native_func(|_vm, _args| Err(unsupported("generateMessagingPreferencesUrl"))),+ );++ fns+ })+ .clone()+}++// Mirrors transformation-functions.ts cleanNullValuesInternal: strip nulls from arrays and+// objects, leave values past MAX_DEPTH untouched.+fn clean_null_values(value: Value, depth: usize) -> Value {+ if depth > CLEAN_NULL_VALUES_MAX_DEPTH {+ return value;+ }+ match value {+ Value::Array(items) => Value::Array(+ items+ .into_iter()+ .map(|item| clean_null_values(item, depth + 1))+ .filter(|item| !item.is_null())+ .collect(),+ ),+ Value::Object(entries) => Value::Object(+ entries+ .into_iter()+ .map(|(key, item)| (key, clean_null_values(item, depth + 1)))+ .filter(|(_, item)| !item.is_null())+ .collect(),+ ),+ other => other,+ }+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::*;++ #[test]+ fn clean_null_values_strips_null_entries_within_the_depth_budget() {+ // Mirrors the Node reference: a null child is dropped by its parent's filter even when the+ // child itself was visited past MAX_DEPTH, so nulls up to 4 levels deep are stripped.+ let input = json!({ "l2": { "l3": { "l4": null }, "keep": null } });+ assert_eq!(clean_null_values(input, 1), json!({ "l2": { "l3": {} } }));+ }++ #[test]+ fn clean_null_values_preserves_nulls_inside_containers_past_max_depth() {+ // The container at depth 4 is returned verbatim, so the null nested inside it survives.+ let input = json!({ "a": { "b": { "c": { "d": null } } } });+ assert_eq!(+ clean_null_values(input.clone(), 1),+ json!({ "a": { "b": { "c": { "d": null } } } })+ );+ }+}diff --git a/rust/common/hogvm/node/src/geoip.rs b/rust/common/hogvm/node/src/geoip.rsnew file mode 100644index 000000000000..26495054cfd7--- /dev/null+++ b/rust/common/hogvm/node/src/geoip.rs@@ -0,0 +1,200 @@+//! GeoIP City lookups shaped like @maxmind/geoip2-node's City model (camelCase keys), which is+//! what the Node VM hands to hog code.++use std::collections::BTreeMap;+use std::net::IpAddr;+use std::sync::OnceLock;++use maxminddb::geoip2;+use serde_json::{json, Map, Value};++static GEOIP: OnceLock<maxminddb::Reader<Vec<u8>>> = OnceLock::new();++/// Open the mmdb once at `init`; later calls are ignored.+pub fn init_geoip(path: &str) -> Result<(), String> {+ if GEOIP.get().is_none() {+ let reader = maxminddb::Reader::open_readfile(path)+ .map_err(|e| format!("failed to open mmdb at {path}: {e}"))?;+ let _ = GEOIP.set(reader);+ }+ Ok(())+}++pub fn is_initialized() -> bool {+ GEOIP.get().is_some()+}++/// City lookup returning the geoip2-node-shaped record, or None the way the Node side returns+/// null (unparsable IP, record not found).+pub fn lookup(ip: &str) -> Option<Value> {+ let reader = GEOIP.get()?;+ let ip = ip.parse::<IpAddr>().ok()?;+ let (city, prefix_len) = reader.lookup_prefix::<geoip2::City>(ip).ok()?;+ Some(city_to_json(&city, ip, prefix_len))+}++// Only fields present in the record are emitted, except `traits`, which geoip2-node always emits+// with false-defaulted flags plus ipAddress/network.+fn city_to_json(city: &geoip2::City, ip: IpAddr, prefix_len: usize) -> Value {+ let mut out = Map::new();++ if let Some(c) = &city.city {+ let mut obj = Map::new();+ insert_some(&mut obj, "geonameId", c.geoname_id.map(|v| json!(v)));+ insert_some(&mut obj, "names", names_to_json(&c.names));+ insert_obj(&mut out, "city", obj);+ }+ if let Some(c) = &city.continent {+ let mut obj = Map::new();+ insert_some(&mut obj, "code", c.code.map(|v| json!(v)));+ insert_some(&mut obj, "geonameId", c.geoname_id.map(|v| json!(v)));+ insert_some(&mut obj, "names", names_to_json(&c.names));+ insert_obj(&mut out, "continent", obj);+ }+ if let Some(c) = &city.country {+ insert_obj(&mut out, "country", country_to_map(c));+ }+ if let Some(c) = &city.registered_country {+ insert_obj(&mut out, "registeredCountry", country_to_map(c));+ }+ if let Some(l) = &city.location {+ let mut obj = Map::new();+ insert_some(+ &mut obj,+ "accuracyRadius",+ l.accuracy_radius.map(|v| json!(v)),+ );+ insert_some(&mut obj, "latitude", l.latitude.map(|v| json!(v)));+ insert_some(&mut obj, "longitude", l.longitude.map(|v| json!(v)));+ insert_some(&mut obj, "metroCode", l.metro_code.map(|v| json!(v)));+ insert_some(&mut obj, "timeZone", l.time_zone.map(|v| json!(v)));+ insert_obj(&mut out, "location", obj);+ }+ if let Some(p) = &city.postal {+ let mut obj = Map::new();+ insert_some(&mut obj, "code", p.code.map(|v| json!(v)));+ insert_obj(&mut out, "postal", obj);+ }+ if let Some(subdivisions) = &city.subdivisions {+ let subs: Vec<Value> = subdivisions+ .iter()+ .map(|s| {+ let mut obj = Map::new();+ insert_some(&mut obj, "geonameId", s.geoname_id.map(|v| json!(v)));+ insert_some(&mut obj, "isoCode", s.iso_code.map(|v| json!(v)));+ insert_some(&mut obj, "names", names_to_json(&s.names));+ Value::Object(obj)+ })+ .collect();+ if !subs.is_empty() {+ out.insert("subdivisions".to_string(), Value::Array(subs));+ }+ }+ out.insert(+ "traits".to_string(),+ traits_to_json(city.traits.as_ref(), ip, prefix_len),+ );++ Value::Object(out)+}++fn traits_to_json(traits: Option<&geoip2::city::Traits>, ip: IpAddr, prefix_len: usize) -> Value {+ let is_anonymous_proxy = traits.and_then(|t| t.is_anonymous_proxy).unwrap_or(false);+ let is_satellite_provider = traits+ .and_then(|t| t.is_satellite_provider)+ .unwrap_or(false);+ json!({+ "isAnonymous": false,+ "isAnonymousProxy": is_anonymous_proxy,+ "isAnonymousVpn": false,+ "isHostingProvider": false,+ "isLegitimateProxy": false,+ "isPublicProxy": false,+ "isResidentialProxy": false,+ "isSatelliteProvider": is_satellite_provider,+ "isTorExitNode": false,+ "ipAddress": ip.to_string(),+ "network": network_string(ip, prefix_len),+ })+}++// The CIDR of the mmdb record that matched the lookup, normalized to the network address the way+// geoip2-node reports it (e.g. "89.160.0.0/17").+fn network_string(ip: IpAddr, prefix_len: usize) -> String {+ let masked = match ip {+ IpAddr::V4(v4) => {+ let bits = u32::from(v4);+ let mask = if prefix_len == 0 {+ 0+ } else {+ u32::MAX << (32 - prefix_len as u32)+ };+ IpAddr::V4((bits & mask).into())+ }+ IpAddr::V6(v6) => {+ let bits = u128::from(v6);+ let mask = if prefix_len == 0 {+ 0+ } else {+ u128::MAX << (128 - prefix_len as u32)+ };+ IpAddr::V6((bits & mask).into())+ }+ };+ format!("{masked}/{prefix_len}")+}++fn country_to_map(country: &geoip2::city::Country) -> Map<String, Value> {+ let mut obj = Map::new();+ insert_some(&mut obj, "geonameId", country.geoname_id.map(|v| json!(v)));+ insert_some(+ &mut obj,+ "isInEuropeanUnion",+ country.is_in_european_union.map(|v| json!(v)),+ );+ insert_some(&mut obj, "isoCode", country.iso_code.map(|v| json!(v)));+ insert_some(&mut obj, "names", names_to_json(&country.names));+ obj+}++fn names_to_json(names: &Option<BTreeMap<&str, &str>>) -> Option<Value> {+ names.as_ref().map(|names| {+ Value::Object(+ names+ .iter()+ .map(|(locale, name)| (locale.to_string(), json!(name)))+ .collect(),+ )+ })+}++fn insert_some(obj: &mut Map<String, Value>, key: &str, value: Option<Value>) {+ if let Some(value) = value {+ obj.insert(key.to_string(), value);+ }+}++fn insert_obj(out: &mut Map<String, Value>, key: &str, obj: Map<String, Value>) {+ if !obj.is_empty() {+ out.insert(key.to_string(), Value::Object(obj));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn network_string_masks_to_the_record_prefix() {+ assert_eq!(+ network_string("89.160.20.129".parse().unwrap(), 17),+ "89.160.0.0/17"+ );+ assert_eq!(network_string("1.2.3.4".parse().unwrap(), 32), "1.2.3.4/32");+ assert_eq!(network_string("1.2.3.4".parse().unwrap(), 0), "0.0.0.0/0");+ assert_eq!(+ network_string("2001:db8:1234::1".parse().unwrap(), 32),+ "2001:db8::/32"+ );+ }+}diff --git a/rust/common/hogvm/node/src/lib.rs b/rust/common/hogvm/node/src/lib.rsnew file mode 100644index 000000000000..e9faca50cad4--- /dev/null+++ b/rust/common/hogvm/node/src/lib.rs@@ -0,0 +1,104 @@+//! Rust HogVM exposed to Node via napi-rs, for shadow execution of ingestion transformations.+//!+//! The Node VM stays authoritative; this binding runs the same (bytecode, globals) pairs on the+//! Rust VM so the caller can compare latency and correctness. `executeBatch` crosses the FFI+//! boundary once per batch, runs off the JS event loop (libuv worker via `AsyncTask`), and can fan+//! out over a rayon thread pool.+//!+//! 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.++mod exec;+mod ext_fns;+mod geoip;++#[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;+#[cfg(not(feature = "noop"))]+use serde_json::Value;++pub use exec::{run_batch, HogExecResult};++#[napi(object)]+pub struct InitOptions {+ pub mmdb_path: Option<String>,+ pub known_bot_ua_list: Option<Vec<String>>,+ pub known_bot_ip_list: Option<Vec<String>>,+}++/// Load process-wide state for the transformation host functions. Idempotent; only the first call+/// takes effect.+#[napi]+pub fn init(options: InitOptions) -> NapiResult<()> {+ if let Some(path) = options.mmdb_path {+ geoip::init_geoip(&path).map_err(napi::Error::from_reason)?;+ }+ ext_fns::set_bot_lists(options.known_bot_ua_list, options.known_bot_ip_list);+ 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),+ })+}