: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: add randomFloat() to hogql (#60038)
Christian Rafferty8dd554a87ee7
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 23d438c1b3e2..b00945cf3260 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -2,6 +2,7 @@ import reimport jsonimport mathimport time+import randomimport datetimeimport dataclassesfrom collections.abc import Callable@@ -327,6 +328,10 @@ def generateUUIDv4(args: list[Any], team: Optional["Team"], stdout: Optional[lisreturn str(uuid.uuid4())+def randomFloat(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> float:+ return random.random()++def keys(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> list:obj = args[0]if isinstance(obj, dict):@@ -1027,6 +1032,7 @@ STL: dict[str, STLFunction] = {"trimRight": STLFunction(fn=trimRight, minArgs=1, maxArgs=2),"splitByString": STLFunction(fn=splitByString, minArgs=2, maxArgs=3),"generateUUIDv4": STLFunction(fn=generateUUIDv4, minArgs=0, maxArgs=0),+ "randomFloat": STLFunction(fn=randomFloat, minArgs=0, maxArgs=0),"sha256Hex": STLFunction(fn=lambda args, team, stdout, timeout: sha256(args[0]), minArgs=1, maxArgs=1),"sha256": STLFunction(fn=lambda args, team, stdout, timeout: sha256(args[0], args[1] if len(args) > 1 else "hex"),diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 338b5968f65d..51a51c2ce051 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -670,6 +670,12 @@ class TestBytecodeExecute:assert self._run_program("if (lower('Tdd4gh') == 'tdd4gh') return upper('test');") == "TEST"assert self._run_program("return reverse('spinner');") == "rennips"+ def test_random_float(self):+ for _ in range(50):+ value = self._run_program("return randomFloat();")+ assert isinstance(value, float)+ assert 0.0 <= value < 1.0+def test_bytecode_empty_statements(self):assert self._run_program(";") is Noneassert self._run_program(";;") is Nonediff --git a/common/hogvm/typescript/src/__tests__/execute.test.ts b/common/hogvm/typescript/src/__tests__/execute.test.tsindex 81d5d45dd8e9..26127fd040ce 100644--- a/common/hogvm/typescript/src/__tests__/execute.test.ts+++ b/common/hogvm/typescript/src/__tests__/execute.test.ts@@ -102,6 +102,11 @@ describe('hogvm execute', () => {expect(execSync(['_h', op.STRING, 'bla', op.CALL_GLOBAL, 'toFloat', 1], options)).toBe(null)expect(execSync(['_h', op.STRING, 'asd', op.CALL_GLOBAL, 'toUUID', 1], options)).toBe('asd')+ const r = execSync(['_h', op.CALL_GLOBAL, 'randomFloat', 0], options) as number+ expect(typeof r).toBe('number')+ expect(r).toBeGreaterThanOrEqual(0)+ expect(r).toBeLessThan(1)+expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.EQ], options)).toBe(false)expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.NOT_EQ], options)).toBe(true)})diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.tsindex 3a5bc013e153..d56fca82e4c9 100644--- a/common/hogvm/typescript/src/stl/stl.ts+++ b/common/hogvm/typescript/src/stl/stl.ts@@ -1099,6 +1099,13 @@ export const STL: Record<string, STLFunction> = {minArgs: 0,maxArgs: 0,},+ randomFloat: {+ fn: () => Math.random(),+ description: 'Returns a uniformly random float in [0, 1). Not cryptographically secure.',+ example: 'randomFloat()',+ minArgs: 0,+ maxArgs: 0,+ },sha256Hex: {fn: ([str], _, options) => sha256(str, 'hex', options),description: 'Computes SHA-256 hash of a string',diff --git a/posthog/hogql/compiler/javascript_stl.py b/posthog/hogql/compiler/javascript_stl.pyindex 81f8052dea4e..1cb9b2760049 100644--- a/posthog/hogql/compiler/javascript_stl.py+++ b/posthog/hogql/compiler/javascript_stl.py@@ -309,6 +309,7 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {"function generateUUIDv4 () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0; const v = c === 'x' ? r : (r & 0x3) | 0x8; return v.toString(16) })}",[],],+ "randomFloat": ["function randomFloat () { return Math.random() }", []],"sha256Hex": ['function sha256Hex(data) {if (data === null || data == undefined) return null; let h0=0x6a09e667,h1=0xbb67ae85,h2=0x3c6ef372,h3=0xa54ff53a,h4=0x510e527f,h5=0x9b05688c,h6=0x1f83d9ab,h7=0x5be0cd19,tsz=0,bp=0;const k=[0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2],rrot=(x,n)=>(x>>>n)|(x<<(32-n)),w=new Uint32Array(64),buf=new Uint8Array(64),process=()=>{for(let j=0,r=0;j<16;j++,r+=4){w[j]=(buf[r]<<24)|(buf[r+1]<<16)|(buf[r+2]<<8)|buf[r+3]}for(let j=16;j<64;j++){let s0=rrot(w[j-15],7)^rrot(w[j-15],18)^(w[j-15]>>>3);let s1=rrot(w[j-2],17)^rrot(w[j-2],19)^(w[j-2]>>>10);w[j]=(w[j-16]+s0+w[j-7]+s1)|0}let a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7;for(let j=0;j<64;j++){let S1=rrot(e,6)^rrot(e,11)^rrot(e,25),ch=(e&f)^((~e)&g),t1=(h+S1+ch+k[j]+w[j])|0,S0=rrot(a,2)^rrot(a,13)^rrot(a,22),maj=(a&b)^(a&c)^(b&c),t2=(S0+maj)|0;h=g;g=f;f=e;e=(d+t1)|0;d=c;c=b;b=a;a=(t1+t2)|0}h0=(h0+a)|0;h1=(h1+b)|0;h2=(h2+c)|0;h3=(h3+d)|0;h4=(h4+e)|0;h5=(h5+f)|0;h6=(h6+g)|0;h7=(h7+h)|0;bp=0},add=data=>{if(typeof data==="string"){data=typeof TextEncoder==="undefined"?Buffer.from(data):(new TextEncoder).encode(data)}for(let i=0;i<data.length;i++){buf[bp++]=data[i];if(bp===64)process();}tsz+=data.length},digest=()=>{buf[bp++]=0x80;if(bp==64)process();if(bp+8>64){while(bp<64)buf[bp++]=0x00;process()}while(bp<58)buf[bp++]=0x00;let L=tsz*8;buf[bp++]=(L/1099511627776.)&255;buf[bp++]=(L/4294967296.)&255;buf[bp++]=L>>>24;buf[bp++]=(L>>>16)&255;buf[bp++]=(L>>>8)&255;buf[bp++]=L&255;process();let reply=new Uint8Array(32);reply[0]=h0>>>24;reply[1]=(h0>>>16)&255;reply[2]=(h0>>>8)&255;reply[3]=h0&255;reply[4]=h1>>>24;reply[5]=(h1>>>16)&255;reply[6]=(h1>>>8)&255;reply[7]=h1&255;reply[8]=h2>>>24;reply[9]=(h2>>>16)&255;reply[10]=(h2>>>8)&255;reply[11]=h2&255;reply[12]=h3>>>24;reply[13]=(h3>>>16)&255;reply[14]=(h3>>>8)&255;reply[15]=h3&255;reply[16]=h4>>>24;reply[17]=(h4>>>16)&255;reply[18]=(h4>>>8)&255;reply[19]=h4&255;reply[20]=h5>>>24;reply[21]=(h5>>>16)&255;reply[22]=(h5>>>8)&255;reply[23]=h5&255;reply[24]=h6>>>24;reply[25]=(h6>>>16)&255;reply[26]=(h6>>>8)&255;reply[27]=h6&255;reply[28]=h7>>>24;reply[29]=(h7>>>16)&255;reply[30]=(h7>>>8)&255;reply[31]=h7&255;reply.hex=()=>{let res="";reply.forEach(x=>res+=("0"+x.toString(16)).slice(-2));return res};return reply};if(data===undefined)return{add,digest};add(data);return digest().hex()}',[],diff --git a/posthog/hogql/compiler/test/test_javascript.py b/posthog/hogql/compiler/test/test_javascript.pyindex 98d7d001a1d5..73d8a03514ba 100644--- a/posthog/hogql/compiler/test/test_javascript.py+++ b/posthog/hogql/compiler/test/test_javascript.py@@ -115,6 +115,13 @@ class TestJavaScript(BaseTest):stl_code = compiler.get_stl_code()self.assertIn("function concat", stl_code)+ def test_random_float_stl_inlined(self):+ compiler = JavaScriptCompiler()+ compiler.stl_functions.add("randomFloat")+ stl_code = compiler.get_stl_code()+ self.assertIn("function randomFloat", stl_code)+ self.assertIn("Math.random()", stl_code)+def test_sanitize_keywords(self):self.assertEqual(_sanitize_identifier("for"), "__x_for")self.assertEqual(_sanitize_identifier("await"), "__x_await")diff --git a/products/error_tracking/backend/hogvm_stl.py b/products/error_tracking/backend/hogvm_stl.pyindex eba207917e29..88593ebd2563 100644--- a/products/error_tracking/backend/hogvm_stl.py+++ b/products/error_tracking/backend/hogvm_stl.py@@ -15,10 +15,14 @@ RUST_HOGVM_STL = ["indexOf","notEmpty","match",+ "extractRegex","JSONExtract",- "arrayReduce",+ "multiSearchAnyCaseInsensitive",+ "randomFloat","arrayCount",+ "arrayMap","arrayFilter",+ "sortableSemver","arrayExists",- "arrayMap",+ "arrayReduce",]diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 3ebe838ecb0a..4b49021cbacf 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -4152,6 +4152,7 @@ dependencies = [name = "hogvm"version = "0.1.0"dependencies = [+ "rand 0.8.5","regex","serde","serde_json",diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.tomlindex f246960bdad5..5ecc5b9cf343 100644--- a/rust/common/hogvm/Cargo.toml+++ b/rust/common/hogvm/Cargo.toml@@ -11,3 +11,4 @@ serde.workspace = trueserde_json.workspace = truethiserror.workspace = trueregex.workspace = true+rand.workspace = truediff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex ce547a977158..7614c2d5dd67 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -1,6 +1,7 @@use core::str;use std::collections::HashMap;+use rand::Rng;use serde_json::{json, Value as JsonValue};use crate::{@@ -393,6 +394,14 @@ pub fn stl() -> Vec<(String, NativeFunction)> {Ok(HogLiteral::Number(0i64.into()).into())}),),+ (+ "randomFloat",+ native_func(|_vm, args| {+ assert_argc(&args, 0, "randomFloat")?;+ let value: f64 = rand::thread_rng().gen_range(0.0..1.0);+ Ok(HogLiteral::Number(Num::Float(value)).into())+ }),+ ),].into_iter().map(|(name, func)| (name.to_string(), func))