: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
perf(hogvm): cache compiled regexes and trim per-rule context cost (#66608)
José Sequeiraafaa8978fff7
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 7e7a83815ef9..0b455543ddcf 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -4462,6 +4462,8 @@ version = "0.1.0"dependencies = ["chrono","chrono-tz",+ "once_cell",+ "quick_cache","rand 0.8.5","regex","serde",diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.tomlindex 0cd0ad832b14..b808c6952e4e 100644--- a/rust/common/hogvm/Cargo.toml+++ b/rust/common/hogvm/Cargo.toml@@ -14,3 +14,5 @@ regex.workspace = truerand.workspace = truechrono.workspace = truechrono-tz.workspace = true+once_cell.workspace = true+quick_cache.workspace = truediff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex 770ef06ef0bc..0dd807c0d80e 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -1,7 +1,9 @@use core::str;use std::collections::HashMap;+use std::sync::Arc;use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone};+use once_cell::sync::Lazy;use rand::Rng;use serde_json::{json, Value as JsonValue};@@ -20,16 +22,23 @@ pub const TO_STRING_RECURSION_LIMIT: usize = 32;// A "native function" is a function that can be called from within the VM. It takes a list// of arguments, and returns either a value, or null. It's pure (cannot modify the VM state).-pub type NativeFunction = Box<dyn Fn(&HogVM, Vec<HogValue>) -> Result<HogValue, VmError>>;+// `Arc` (not `Box`) so the static registry below can be cloned cheaply per execution context.+pub type NativeFunction =+ Arc<dyn Fn(&HogVM, Vec<HogValue>) -> Result<HogValue, VmError> + Send + Sync>;++// The native and hog STL registries are process-constant: build them once and hand out cheap clones+// instead of reconstructing (and, for the hog STL, re-parsing its bytecode) on every context.+static STL_NATIVE_FNS: Lazy<HashMap<String, NativeFunction>> =+ Lazy::new(|| stl().into_iter().collect());+static HOG_STL_MODULES: Lazy<HashMap<String, Module>> =+ Lazy::new(|| HashMap::from([("stl".to_string(), hog_stl())]));pub fn stl_map() -> HashMap<String, NativeFunction> {- stl().into_iter().collect()+ STL_NATIVE_FNS.clone()}pub fn hog_stl_map() -> HashMap<String, Module> {- let mut res = HashMap::new();- res.insert("stl".to_string(), hog_stl());- res+ HOG_STL_MODULES.clone()}// NOTE - if you make changes to this, be sure to re-run `bin/dump_hogvmrs_stl`@@ -604,7 +613,7 @@ fn err_to_null(/// Helper to construct a HogVM native function from a closure.pub fn native_func<F>(func: F) -> NativeFunctionwhere- F: Fn(&HogVM, Vec<HogValue>) -> Result<HogValue, VmError> + 'static,+ F: Fn(&HogVM, Vec<HogValue>) -> Result<HogValue, VmError> + Send + Sync + 'static,{- Box::new(func)+ Arc::new(func)}diff --git a/rust/common/hogvm/src/util.rs b/rust/common/hogvm/src/util.rsindex 93e1df056579..9603923ffcf4 100644--- a/rust/common/hogvm/src/util.rs+++ b/rust/common/hogvm/src/util.rs@@ -1,4 +1,8 @@-use regex::RegexBuilder;+use std::sync::Arc;++use once_cell::sync::Lazy;+use quick_cache::sync::Cache;+use regex::{Regex, RegexBuilder};use serde_json::Value;use crate::{@@ -7,6 +11,36 @@ use crate::{vm::HogVM,};+// Compiling a regex is orders of magnitude more expensive than matching against an already-compiled+// one, and rule patterns are constant across the events they run on — so compile once and reuse.+// The cache is bounded so dynamically constructed patterns can't grow it without limit, and global+// (rather than per-VM) so a pattern is compiled at most once fleet-wide instead of once per worker.+static REGEX_CACHE: Lazy<Cache<(String, bool), Arc<Regex>>> = Lazy::new(|| Cache::new(8192));++// Patterns longer than this are compiled fresh on every call instead of being cached. A Hog program+// can build a regex from event properties, so without this an attacker could ingest many unique+// large patterns and retain them all in the process-wide cache (bounded by entry count, not bytes).+// Real rule patterns are far shorter than this.+const MAX_CACHEABLE_PATTERN_LEN: usize = 1024;++fn compiled_regex(pattern: &str, case_insensitive: bool) -> Result<Arc<Regex>, VmError> {+ let compile = || {+ RegexBuilder::new(pattern)+ .case_insensitive(case_insensitive)+ .build()+ .map(Arc::new)+ .map_err(|e| VmError::InvalidRegex(pattern.to_string(), e.to_string()))+ };++ if pattern.len() > MAX_CACHEABLE_PATTERN_LEN {+ return compile();+ }++ // `get_or_insert_with` computes at most once per key even under concurrent first access, so two+ // threads racing the same cold pattern don't both compile, and a failed compile isn't cached.+ REGEX_CACHE.get_or_insert_with(&(pattern.to_owned(), case_insensitive), compile)+}+pub fn like(val: impl AsRef<str>,pattern: impl AsRef<str>,@@ -21,12 +55,7 @@ pub fn regex_match(pattern: impl AsRef<str>,case_sensitive: bool,) -> Result<bool, VmError> {- let mut builder = RegexBuilder::new(pattern.as_ref());- // TODO - this is expensive, but I'm not keen on optimizing it right now- let regex = builder- .case_insensitive(!case_sensitive)- .build()- .map_err(|e| VmError::InvalidRegex(pattern.as_ref().to_string(), e.to_string()))?;+ let regex = compiled_regex(pattern.as_ref(), !case_sensitive)?;Ok(regex.is_match(val.as_ref()))}@@ -34,9 +63,7 @@ pub fn regex_extract(haystack: impl AsRef<str>,pattern: impl AsRef<str>,) -> Result<String, VmError> {- let regex = RegexBuilder::new(pattern.as_ref())- .build()- .map_err(|e| VmError::InvalidRegex(pattern.as_ref().to_string(), e.to_string()))?;+ let regex = compiled_regex(pattern.as_ref(), false)?;let Some(captures) = regex.captures(haystack.as_ref()) else {return Ok(String::new());};@@ -201,4 +228,48 @@ mod tests {assert!(like("hello\\there", "hello\\there", true).unwrap());assert!(like("hello\\x", "hello\\x", true).unwrap());}++ #[test]+ fn test_compiled_regex_is_cached() {+ // Same (pattern, case) must hand back the same compiled regex instead of recompiling.+ let a = compiled_regex("foo.*bar", false).unwrap();+ let b = compiled_regex("foo.*bar", false).unwrap();+ assert!(Arc::ptr_eq(&a, &b));++ // Case variants are distinct cache entries, not aliases.+ let insensitive = compiled_regex("foo.*bar", true).unwrap();+ assert!(!Arc::ptr_eq(&a, &insensitive));+ }++ #[test]+ fn test_oversized_patterns_are_not_cached() {+ // Patterns past the length cap still compile and match correctly, but are recompiled each+ // call rather than retained — so large attacker-controlled patterns can't accumulate.+ let big = "x".repeat(MAX_CACHEABLE_PATTERN_LEN + 1);+ let a = compiled_regex(&big, false).unwrap();+ let b = compiled_regex(&big, false).unwrap();+ assert!(!Arc::ptr_eq(&a, &b), "oversized pattern must not be cached");+ assert!(regex_match(&big, &big, true).unwrap()); // the literal still matches itself+ }++ #[test]+ fn test_regex_match_case_sensitivity() {+ assert!(regex_match("Hello", "hello", false).unwrap()); // case-insensitive matches+ assert!(!regex_match("Hello", "hello", true).unwrap()); // case-sensitive does not+ }++ #[test]+ fn test_invalid_regex_errors() {+ assert!(matches!(+ regex_match("anything", "(unclosed", true),+ Err(VmError::InvalidRegex(..))+ ));+ }++ #[test]+ fn test_regex_extract_uses_cache() {+ assert_eq!(regex_extract("id=42;", r"id=(\d+)").unwrap(), "42");+ // Second call exercises the cached compilation path and stays correct.+ assert_eq!(regex_extract("id=7;", r"id=(\d+)").unwrap(), "7");+ }}diff --git a/rust/cymbal/src/modes/processing/rules/assignment.rs b/rust/cymbal/src/modes/processing/rules/assignment.rsindex bf39cfe4e012..ce98428860f5 100644--- a/rust/cymbal/src/modes/processing/rules/assignment.rs+++ b/rust/cymbal/src/modes/processing/rules/assignment.rs@@ -1,5 +1,3 @@-use std::collections::HashMap;-use chrono::{DateTime, Utc};use common_types::TeamId;use hogvm::{ExecutionContext, Program, StepOutcome, VmError};@@ -179,11 +177,10 @@ impl AssignmentRule {}};- let mut globals = HashMap::new();- globals.insert("issue".to_string(), issue.clone());- globals.insert("properties".to_string(), props.clone());- let globals: Value = serde_json::to_value(globals)- .expect("Can construct a json object from a hashmap of String:JsonValue");+ let globals = Value::Object(serde_json::Map::from_iter([+ ("issue".to_string(), issue.clone()),+ ("properties".to_string(), props.clone()),+ ]));let program = Program::new(rule_bytecode.clone())?;let context = ExecutionContext::with_defaults(program).with_globals(globals);let mut vm = context.to_vm()?;diff --git a/rust/cymbal/src/modes/processing/rules/grouping.rs b/rust/cymbal/src/modes/processing/rules/grouping.rsindex 7f9f1f61a863..a43c41ac0e69 100644--- a/rust/cymbal/src/modes/processing/rules/grouping.rs+++ b/rust/cymbal/src/modes/processing/rules/grouping.rs@@ -1,5 +1,3 @@-use std::collections::HashMap;-use chrono::{DateTime, Utc};use common_types::TeamId;use hogvm::{ExecutionContext, Program, StepOutcome, VmError};@@ -95,10 +93,10 @@ impl GroupingRule {}};- let mut globals = HashMap::new();- globals.insert("properties".to_string(), props.clone());- let globals: Value = serde_json::to_value(globals)- .expect("Can construct a json object from a hashmap of String:JsonValue");+ let globals = Value::Object(serde_json::Map::from_iter([(+ "properties".to_string(),+ props.clone(),+ )]));let program = Program::new(rule_bytecode.clone())?;let context = ExecutionContext::with_defaults(program).with_globals(globals);let mut vm = context.to_vm()?;diff --git a/rust/cymbal/src/modes/processing/rules/suppression.rs b/rust/cymbal/src/modes/processing/rules/suppression.rsindex c5f908a793d7..69fa0795960c 100644--- a/rust/cymbal/src/modes/processing/rules/suppression.rs+++ b/rust/cymbal/src/modes/processing/rules/suppression.rs@@ -1,5 +1,3 @@-use std::collections::HashMap;-use chrono::{DateTime, Utc};use common_types::TeamId;use hogvm::{ExecutionContext, Program, StepOutcome, VmError};@@ -103,10 +101,10 @@ impl SuppressionRule {}};- let mut globals = HashMap::new();- globals.insert("properties".to_string(), props.clone());- let globals: Value = serde_json::to_value(globals)- .expect("Can construct a json object from a hashmap of String:JsonValue");+ let globals = Value::Object(serde_json::Map::from_iter([(+ "properties".to_string(),+ props.clone(),+ )]));let program = Program::new(rule_bytecode.clone())?;let context = ExecutionContext::with_defaults(program).with_globals(globals);let mut vm = context.to_vm()?;