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.

fix(hogvm): check range length before building the array (#107514)

Meikel Ratzb5b7a42143d9
diff --git a/common/hogvm/CHANGELOG.md b/common/hogvm/CHANGELOG.md
index f2e61b24d859..ec5eae6b9e99 100644
--- a/common/hogvm/CHANGELOG.md
+++ b/common/hogvm/CHANGELOG.md
@@ -1,5 +1,11 @@
# HogQL bytecode changelog
+## 2026-09-28 - 1.0.71
+
+`range` checks the requested length against the memory limit before it builds the array, as the
+Python VM does. A range past the limit fails with the `Memory limit ... exceeded` error. No bytecode
+operations changed.
+
## 2026-09-07 - 1.0.70
Eleven standard library functions accept the trailing arguments that HogQL accepts. No bytecode
diff --git a/common/hogvm/typescript/package.json b/common/hogvm/typescript/package.json
index 8dc427b197d0..ff69bb6dc18a 100644
--- a/common/hogvm/typescript/package.json
+++ b/common/hogvm/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@posthog/hogvm",
- "version": "1.0.70",
+ "version": "1.0.71",
"description": "PostHog Hog Virtual Machine",
"license": "MIT",
"author": "PostHog <[email protected]>",
diff --git a/common/hogvm/typescript/src/__tests__/execute.test.ts b/common/hogvm/typescript/src/__tests__/execute.test.ts
index 2e3d3a7dc697..daa0b40a3ce5 100644
--- a/common/hogvm/typescript/src/__tests__/execute.test.ts
+++ b/common/hogvm/typescript/src/__tests__/execute.test.ts
@@ -509,6 +509,73 @@ describe('hogvm execute', () => {
)
})
+ const billionRange = ['_H', 1, op.INTEGER, 0, op.INTEGER, 1_000_000_000, op.CALL_GLOBAL, 'range', 2, op.RETURN]
+
+ test.each([
+ ['range(0, 1000000000)', billionRange, {}],
+ [
+ '(range)(0, 1000000000)',
+ [
+ '_H',
+ 1,
+ op.INTEGER,
+ 0,
+ op.INTEGER,
+ 1_000_000_000,
+ op.STRING,
+ 'range',
+ op.GET_GLOBAL,
+ 1,
+ op.CALL_LOCAL,
+ 2,
+ op.RETURN,
+ ],
+ {},
+ ],
+ ['range(0, 1000000000) with the memory limit off', billionRange, { memoryLimit: 0 }],
+ [
+ 'range(0, 200) after a retained string',
+ [
+ '_H',
+ 1,
+ op.STRING,
+ 'x'.repeat(1000),
+ op.INTEGER,
+ 0,
+ op.INTEGER,
+ 200,
+ op.CALL_GLOBAL,
+ 'range',
+ 2,
+ op.RETURN,
+ op.POP,
+ ],
+ { memoryLimit: 2048 },
+ ],
+ [
+ "range('000…0', 10) of long strings",
+ ['_H', 1, op.STRING, '0'.repeat(100), op.INTEGER, 10, op.CALL_GLOBAL, 'range', 2, op.RETURN],
+ { memoryLimit: 1000 },
+ ],
+ ])('%s is refused before the array is built', (_name, bytecode, options) => {
+ // A real oversized range stops the process with a fatal V8 error, so the spy fails every allocation.
+ const arrayFrom = jest.spyOn(Array, 'from').mockImplementation(() => {
+ throw new Error('Allocated range')
+ })
+ let error: unknown
+ try {
+ execSync(bytecode, options)
+ } catch (e) {
+ error = e
+ } finally {
+ arrayFrom.mockRestore()
+ }
+ expect(error).toMatchObject({
+ kind: 'limit',
+ message: expect.stringMatching(/^Memory limit of \d+ bytes exceeded/),
+ })
+ })
+
test('should execute user-defined stringify function correctly', async () => {
const functions = {
stringify: (arg: any) => {
diff --git a/common/hogvm/typescript/src/execute.ts b/common/hogvm/typescript/src/execute.ts
index 648d2b6ce388..dff8eebd2315 100644
--- a/common/hogvm/typescript/src/execute.ts
+++ b/common/hogvm/typescript/src/execute.ts
@@ -16,6 +16,7 @@ import {
ExecOptions,
ExecResult,
HogUpValue,
+ STLFunction,
Telemetry,
ThrowFrame,
VMState,
@@ -292,19 +293,34 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
return stack.pop()
}
+ function memoryLimitExceeded(attempted: number): HogVMException {
+ return new HogVMException(
+ `Memory limit of ${memLimit} bytes exceeded. Tried to allocate ${attempted} bytes.`,
+ 'limit'
+ )
+ }
+
function pushStack(value: any): any {
memStack.push(calculateCost(value))
memUsed += memStack[memStack.length - 1]
maxMemUsed = Math.max(maxMemUsed, memUsed)
if (memUsed > memLimit && memLimit > 0) {
- throw new HogVMException(
- `Memory limit of ${memLimit} bytes exceeded. Tried to allocate ${memUsed} bytes.`,
- 'limit'
- )
+ throw memoryLimitExceeded(memUsed)
}
return stack.push(value)
}
+ // pushStack charges a result after it is built, which is too late for a result the heap cannot hold.
+ function callStlWithinMemory(stlFn: STLFunction, args: any[], name: string): any {
+ if (stlFn.memoryCost && memLimit > 0) {
+ const attempted = memUsed + stlFn.memoryCost(args)
+ if (attempted > memLimit) {
+ throw memoryLimitExceeded(attempted)
+ }
+ }
+ return callStl(stlFn.fn, args, name, options)
+ }
+
function spliceStack2(start: number, deleteCount?: number): any[] {
memUsed -= memStack.splice(start, deleteCount).reduce((acc, val) => acc + val, 0)
return stack.splice(start, deleteCount)
@@ -941,7 +957,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
.fill(null)
.map(() => popStack())
: stackKeepFirstElements(stack.length - temp)
- pushStack(callStl(stlFn.fn, args, name, options))
+ pushStack(callStlWithinMemory(stlFn, args, name))
} else if (Object.hasOwn(BYTECODE_STL, name)) {
const argNames = BYTECODE_STL[name][0]
if (argNames.length !== temp) {
@@ -1053,7 +1069,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
args.push(null)
}
}
- pushStack(callStl(stlFn.fn, args, closure.callable.name, options))
+ pushStack(callStlWithinMemory(stlFn, args, closure.callable.name))
} else if (closure.callable.__hogCallable__ === 'async') {
if (asyncSteps >= maxAsyncSteps) {
throw new HogVMException(
diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.ts
index 3dfba60a37a4..9bb7066bfa46 100644
--- a/common/hogvm/typescript/src/stl/stl.ts
+++ b/common/hogvm/typescript/src/stl/stl.ts
@@ -1,8 +1,9 @@
import { DateTime } from 'luxon'
+import { DEFAULT_MAX_MEMORY } from '../constants'
import { isHogAST, isHogCallable, isHogClosure, isHogDate, isHogDateTime, isHogError, newHogError } from '../objects'
-import { AsyncSTLFunction, HogDate, HogDateTime, HogInterval, STLFunction } from '../types'
-import { HogVMException, getNestedValue, like } from '../utils'
+import { AsyncSTLFunction, ExecOptions, HogDate, HogDateTime, HogInterval, STLFunction } from '../types'
+import { COST_PER_UNIT, HogVMException, calculateCost, getNestedValue, like } from '../utils'
import { md5, sha1, sha1HmacChain, sha256, sha256HmacChain } from './crypto'
import {
formatDateTime,
@@ -412,7 +413,29 @@ function toDateTimeFromDate(date: HogDate): HogDateTime {
}
}
-function rangeFn(args: any[]): any[] {
+// `Array.from` truncates the length and treats a negative or NaN length as 0.
+function rangeLength(args: any[]): number {
+ const length = Math.trunc(args.length === 1 ? Number(args[0]) : args[1] - args[0])
+ return length > 0 ? length : 0
+}
+
+// `args[0] + i` builds strings when `args[0]` is a string. The last element is the longest, so its cost prices every element.
+function rangeMemoryCost(args: any[]): number {
+ const length = rangeLength(args)
+ if (length === 0) {
+ return COST_PER_UNIT
+ }
+ const last = args.length === 1 ? length - 1 : args[0] + (length - 1)
+ return COST_PER_UNIT + length * calculateCost(last)
+}
+
+// The VM skips the `memoryCost` check when the caller turns the limit off, so the default limit applies then.
+function rangeFn(args: any[], _name: string, options?: ExecOptions): any[] {
+ const limit = options?.memoryLimit && options.memoryLimit > 0 ? options.memoryLimit : DEFAULT_MAX_MEMORY
+ const cost = rangeMemoryCost(args)
+ if (cost > limit) {
+ throw new HogVMException(`Memory limit of ${limit} bytes exceeded. Tried to allocate ${cost} bytes.`, 'limit')
+ }
if (args.length === 1) {
return Array.from({ length: args[0] }, (_, i) => i)
}
@@ -1704,6 +1727,7 @@ export const STL: Record<string, STLFunction> = {
example: 'range($1, $2)',
minArgs: 1,
maxArgs: 2,
+ memoryCost: rangeMemoryCost,
},
round: {
fn: roundFn,
diff --git a/common/hogvm/typescript/src/types.ts b/common/hogvm/typescript/src/types.ts
index 949cb8cc73a6..a554932877ad 100644
--- a/common/hogvm/typescript/src/types.ts
+++ b/common/hogvm/typescript/src/types.ts
@@ -160,6 +160,8 @@ export interface STLFunction {
example: string
minArgs?: number
maxArgs?: number
+ // Memory the result will cost, so the VM can refuse the call before the function builds the result
+ memoryCost?: (args: any[]) => number
}
export interface AsyncSTLFunction {
diff --git a/common/hogvm/typescript/src/utils.ts b/common/hogvm/typescript/src/utils.ts
index b338fc11acaf..dbb33571dea7 100644
--- a/common/hogvm/typescript/src/utils.ts
+++ b/common/hogvm/typescript/src/utils.ts
@@ -49,7 +49,7 @@ export class UncaughtHogVMException extends HogVMException {
}
/** Fixed cost per object in memory */
-const COST_PER_UNIT = 8
+export const COST_PER_UNIT = 8
export function like(
string: string,
diff --git a/rust/common/hogvm/src/memory.rs b/rust/common/hogvm/src/memory.rs
index bd1ffe84b7f6..8b204c6aa959 100644
--- a/rust/common/hogvm/src/memory.rs
+++ b/rust/common/hogvm/src/memory.rs
@@ -46,7 +46,7 @@ impl VmHeap {
self.peak_bytes = self.peak_bytes.max(bytes);
}
- fn assert_can_allocate(&self, new_bytes: usize) -> Result<(), VmError> {
+ pub(crate) fn assert_can_allocate(&self, new_bytes: usize) -> Result<(), VmError> {
if self.current_bytes.saturating_add(new_bytes) > self.max_bytes {
Err(VmError::OutOfResource("Heap Memory".to_string()))
} else {
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 7ba2ec35372a..c3e8dc9dc83d 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -730,6 +730,12 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer(),
)
};
+ // Budget the Vec before collect, because walk_emplacing charges the heap only after it exists.
+ let len = usize::try_from(end.saturating_sub(start).max(0)).unwrap_or(usize::MAX);
+ let bytes = len
+ .checked_mul(std::mem::size_of::<HogValue>())
+ .ok_or_else(|| VmError::OutOfResource("Heap Memory".to_string()))?;
+ vm.heap.assert_can_allocate(bytes)?;
let arr = (start..end)
.map(|i| HogLiteral::Number(Num::Integer(i)).into())
.collect();
diff --git a/rust/common/hogvm/tests/range_limit.rs b/rust/common/hogvm/tests/range_limit.rs
new file mode 100644
index 000000000000..1714562ff687
--- /dev/null
+++ b/rust/common/hogvm/tests/range_limit.rs
@@ -0,0 +1,36 @@
+//! A range past the heap limit must fail with OutOfResource before the VM builds it, not abort the process.
+
+use hogvm::{sync_execute, ExecutionContext, Program, VmError};
+use serde_json::json;
+
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+
+#[test]
+fn range_past_the_heap_limit_is_refused_before_it_is_built() {
+ // With no heap limit (usize::MAX), only an overflow check refuses a length whose byte size overflows.
+ for (length, max_heap_size) in [(1_000_000_000_000_i64, 1024 * 1024), (i64::MAX, usize::MAX)] {
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_INTEGER),
+ json!(length),
+ json!(OP_CALL_GLOBAL),
+ json!("range"),
+ json!(1),
+ json!(OP_RETURN),
+ ];
+
+ let program = Program::new(bc).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_globals(json!({}))
+ .with_max_heap_size(max_heap_size);
+ let failure = sync_execute(&ctx, false).expect_err("range past the heap limit must fail");
+ assert!(
+ matches!(failure.error, VmError::OutOfResource(_)),
+ "range({length}) with a {max_heap_size}-byte heap: expected OutOfResource, got {:?}",
+ failure.error
+ );
+ }
+}