Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(cohorts): optimize cohort stream processor (#66849)

Matheus Batista42c14723e8be
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 342c1bf9ae97..856c08ed0da2 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -229,6 +229,14 @@ pub struct Config {
#[envconfig(default = "5000")]
pub offset_commit_interval_ms: u64,
+ /// Tokio runtime worker threads. `0` (default) lets Tokio size the pool from
+ /// `available_parallelism()`, which accounts for a CFS CPU *limit* (`cpu.max`) but not CPU
+ /// *requests*/shares — so on a requests-only pod (no `limits.cpu`), or when the cgroup fs isn't
+ /// readable, it returns the *node's* core count and over-subscribes the runtime. Set this to the
+ /// pod's CPU budget to cap the pool regardless of how the limit is expressed.
+ #[envconfig(default = "0")]
+ pub tokio_worker_threads: usize,
+
/// How often the sweep fires to evict state whose eviction deadline has passed.
#[envconfig(default = "30000")]
pub sweep_interval_ms: u64,
@@ -687,6 +695,7 @@ mod tests {
recv_batch_size: 1000,
recv_batch_timeout_ms: 500,
offset_commit_interval_ms: 5000,
+ tokio_worker_threads: 0,
sweep_interval_ms: 30000,
sweep_safety_margin_ms: 300000,
store_path: "cohort-store".to_string(),
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index 499737008225..d106acf2850e 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -741,7 +741,9 @@ fn boot_assignment_settled(assignment: &HashSet<i32>, prev: &mut Option<HashSet<
/// Uses a raw `StreamConsumer` with manual commit because the per-partition `OffsetTracker`
/// commits a `TopicPartitionList` that the `common-kafka` wrapper can't express.
pub struct CohortStreamEventsConsumer {
- consumer: StreamConsumer<CohortConsumerContext>,
+ /// `Arc` so the commit task and consume loop share one consumer; rdkafka supports concurrent
+ /// `recv` and `commit`.
+ consumer: Arc<StreamConsumer<CohortConsumerContext>>,
topic: String,
dispatcher: Arc<EventDispatcher>,
handle: Handle,
@@ -772,7 +774,7 @@ impl CohortStreamEventsConsumer {
restore_manifest: Option<OffsetManifest>,
) -> Self {
Self {
- consumer,
+ consumer: Arc::new(consumer),
topic,
dispatcher,
handle,
@@ -785,13 +787,23 @@ impl CohortStreamEventsConsumer {
}
}
- /// Run until the lifecycle handle signals shutdown. Commit is deadline-driven, not a `select!`
- /// arm, to avoid cancelling an in-flight `consume_batch` and dropping buffered events.
+ /// Run until the lifecycle handle signals shutdown.
+ ///
+ /// Offset commit runs on its own interval task so a CPU-saturated consume loop or worker backlog
+ /// can't block offset advancement; it shares the shutdown signal and is awaited before the final
+ /// synchronous commit. Liveness is reported inline from `handle_outcome`.
pub async fn process(self) {
let _guard = self.handle.process_scope();
info!(topic = %self.topic, "cohort_stream_events consume loop starting");
- let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
+ let commit_task = tokio::spawn(run_commit_loop(
+ self.consumer.clone(),
+ self.dispatcher.clone(),
+ self.topic.clone(),
+ self.offset_commit_interval,
+ self.handle.clone(),
+ ));
+
// One-shot guards; each pre-marked done when its gate is off, keeping the non-durable path unchanged.
let mut boot_sweep_done = !self.dispatcher.durable_restore_enabled();
let mut eager_redrive_done = !self.dispatcher.durable_restore_enabled();
@@ -829,22 +841,15 @@ impl CohortStreamEventsConsumer {
continue;
}
self.handle_outcome(outcome).await;
- let now = tokio::time::Instant::now();
- if now >= commit_deadline {
- fsync_then_commit(
- self.dispatcher.store(),
- &self.consumer,
- self.dispatcher.tracker(),
- self.dispatcher.owned_committable_offsets(),
- &self.topic,
- CommitMode::Async,
- );
- commit_deadline = now + self.offset_commit_interval;
- }
}
}
}
+ // Await the commit task before the final synchronous commit so the two don't race.
+ if let Err(err) = commit_task.await {
+ warn!(error = %err, "offset-commit task did not exit cleanly");
+ }
+
let tracker = self.dispatcher.shutdown().await;
let offsets = self.dispatcher.owned_committable_offsets();
fsync_then_commit(
@@ -1094,6 +1099,35 @@ pub(crate) fn fsync_then_commit<C: ConsumerContext>(
commit_offsets(consumer, tracker, offsets, topic, mode);
}
+/// Flushes the store's WAL and commits the owned committable offsets on a fixed interval, independent
+/// of the consume loop so a stalled loop can't block offset advancement. Exits on shutdown.
+async fn run_commit_loop(
+ consumer: Arc<StreamConsumer<CohortConsumerContext>>,
+ dispatcher: Arc<EventDispatcher>,
+ topic: String,
+ interval: Duration,
+ handle: Handle,
+) {
+ let mut ticker = tokio::time::interval(interval);
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ tokio::select! {
+ biased;
+ _ = handle.shutdown_recv() => break,
+ _ = ticker.tick() => {
+ fsync_then_commit(
+ dispatcher.store(),
+ &consumer,
+ dispatcher.tracker(),
+ dispatcher.owned_committable_offsets(),
+ &topic,
+ CommitMode::Async,
+ );
+ }
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
index 46ea4fdda70f..b430ac4980a7 100644
--- a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
+++ b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
@@ -11,6 +11,11 @@ use crate::filters::CohortId;
use crate::stage1::key::LeafStateKey;
use crate::stage1::pick_state::pick_state_variant;
+/// HogVM `RETURN` opcode, appended to each program at load. Python-compiled cohort bytecode ends at
+/// its root comparison with no `RETURN`, which the Rust VM would hit as `EndOfProgram`. A program
+/// already ending in `RETURN` stops at the first, so the appended one is inert.
+const OP_RETURN: i64 = 38;
+
/// Why a leaf was dropped during parse. Used as the `reason` label on the skip counter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeafDropReason {
@@ -170,7 +175,9 @@ fn condition_hash_bytes(value: Option<&Value>) -> Option<[u8; 16]> {
fn bytecode_array(value: Option<&Value>) -> Option<Arc<Vec<Value>>> {
let array = value?.as_array()?;
- Some(Arc::new(array.clone()))
+ let mut bytecode = array.clone();
+ bytecode.push(Value::from(OP_RETURN));
+ Some(Arc::new(bytecode))
}
/// A referenced cohort id as a JSON number or string-encoded int.
@@ -199,11 +206,18 @@ mod tests {
const HASH: &str = "0123456789abcdef";
- /// A representative bytecode program.
+ /// A representative bytecode program, as compiled (no trailing `RETURN`).
fn bytecode() -> Value {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
+ /// The stored form of [`bytecode`]: the loader appends a trailing `RETURN` (opcode 38).
+ fn bytecode_loaded() -> Vec<Value> {
+ let mut bc = bytecode().as_array().unwrap().clone();
+ bc.push(json!(OP_RETURN));
+ bc
+ }
+
fn hash_bytes() -> [u8; 16] {
*b"0123456789abcdef"
}
@@ -227,7 +241,7 @@ mod tests {
assert_eq!(leaf.event_key, "$pageview");
assert_eq!(leaf.time_value, Some(7));
assert_eq!(leaf.leaf_state_key, LeafStateKey::for_behavioral(&leaf));
- assert_eq!(leaf.bytecode.as_ref(), bytecode().as_array().unwrap());
+ assert_eq!(leaf.bytecode.as_ref(), &bytecode_loaded());
assert_eq!(
leaf.state_variant,
Some(crate::stage1::state::StateVariant::BehavioralSingle),
@@ -468,7 +482,7 @@ mod tests {
};
assert_eq!(leaf.condition_hash, hash_bytes());
assert_eq!(leaf.leaf_state_key, LeafStateKey(hash_bytes()));
- assert_eq!(leaf.bytecode.as_ref(), bytecode().as_array().unwrap());
+ assert_eq!(leaf.bytecode.as_ref(), &bytecode_loaded());
assert_eq!(leaf.raw, node);
}
diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-stream-processor/src/filters/reverse_index.rs
index 6d0fa0f706cc..68dc43e6dd02 100644
--- a/rust/cohort-stream-processor/src/filters/reverse_index.rs
+++ b/rust/cohort-stream-processor/src/filters/reverse_index.rs
@@ -367,6 +367,16 @@ mod tests {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
+ /// HogVM `RETURN` opcode, appended to stored bytecode by the catalog loader.
+ const OP_RETURN: i64 = 38;
+
+ /// The stored form of [`behavioral_bytecode`]: the loader appends a trailing `RETURN` (opcode 38).
+ fn behavioral_bytecode_loaded() -> Vec<Value> {
+ let mut bc = behavioral_bytecode().as_array().unwrap().clone();
+ bc.push(json!(OP_RETURN));
+ bc
+ }
+
/// A `performed_event` leaf on `$pageview` with a tunable window.
fn behavioral_performed_event(time_value: i64) -> Value {
json!({
@@ -516,7 +526,7 @@ mod tests {
.by_condition_to_bytecode
.get(&HASH)
.expect("bytecode captured under the conditionHash");
- assert_eq!(bytecode.as_ref(), behavioral_bytecode().as_array().unwrap());
+ assert_eq!(bytecode.as_ref(), &behavioral_bytecode_loaded());
}
#[test]
diff --git a/rust/cohort-stream-processor/src/hogvm/executor.rs b/rust/cohort-stream-processor/src/hogvm/executor.rs
index ddf65b5c707e..670bacc0e1a6 100644
--- a/rust/cohort-stream-processor/src/hogvm/executor.rs
+++ b/rust/cohort-stream-processor/src/hogvm/executor.rs
@@ -1,5 +1,10 @@
//! Run compiled cohort-filter bytecode through `hogvm::sync_execute`, coercing the result to the
//! boolean Stage 1 needs (matching the Node consumer's `execResult?.result ?? false`).
+//!
+//! The hot path reuses one [`CohortEvaluator`] per event: the STL context and globals are set once
+//! and only the program is swapped per condition, amortizing the context build across all conditions.
+
+use std::sync::Arc;
use hogvm::{sync_execute, ExecutionContext, Program, VmError};
use metrics::counter;
@@ -8,11 +13,8 @@ use tracing::debug;
use crate::observability::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION};
-/// HogVM `RETURN` opcode. See [`evaluate_detailed`] for why it is appended to every program.
-const OP_RETURN: i64 = 38;
-
-/// The classified outcome of evaluating one program; [`evaluate`] collapses this to a `bool` but
-/// the variants preserve *why* a non-match happened.
+/// The classified outcome of evaluating one program; [`CohortEvaluator::evaluate`] collapses this to
+/// a `bool` but the variants preserve *why* a non-match happened.
#[derive(Debug)]
pub enum EvalOutcome {
Matched(bool),
@@ -21,43 +23,83 @@ pub enum EvalOutcome {
VmError(VmError),
}
-/// Evaluate `bytecode` against `globals`, returning the detailed [`EvalOutcome`].
+/// A reusable evaluator owning one [`ExecutionContext`]: set globals once per event, swap the program
+/// per condition, both in place.
///
-/// Cohort bytecode ends with its root comparison op and no `RETURN`. The Rust VM treats running
-/// off the end as `EndOfProgram`; appending a `RETURN` recovers the Python/Node semantic. A
-/// program already ending in `RETURN` finishes first, so the append is safe for both shapes.
+/// Comparisons are coercing (cross-type ordering + epoch temporal ordering/equality) to match the
+/// Python/TS/ClickHouse reference; opt-in, so other `hogvm` consumers like cymbal keep strict ones.
+pub struct CohortEvaluator {
+ context: ExecutionContext,
+}
+
+impl Default for CohortEvaluator {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CohortEvaluator {
+ pub fn new() -> Self {
+ // A bare header is a valid program; `set_program` replaces this seed before the first evaluation.
+ let seed = Program::new(vec![Value::from("_H"), Value::from(1)])
+ .expect("a bare bytecode header is a valid program");
+ let context = ExecutionContext::with_defaults(seed).with_coercing_comparisons();
+ Self { context }
+ }
+
+ /// Move `globals` into the reused context (no clone); one call serves a whole event's conditions.
+ pub fn set_globals(&mut self, globals: Value) {
+ self.context.set_globals(globals);
+ }
+
+ /// Evaluate one condition's bytecode against the current globals, coercing failures and non-bool
+ /// results to `false` and emitting a per-class metric so a silently-failing cohort stays
+ /// observable. `bytecode` must be `RETURN`-terminated (the loader appends it).
+ pub fn evaluate(&mut self, bytecode: Arc<Vec<Value>>) -> bool {
+ outcome_to_bool(self.evaluate_detailed(bytecode))
+ }
+
+ /// As [`Self::evaluate`] but returns the detailed [`EvalOutcome`].
+ pub fn evaluate_detailed(&mut self, bytecode: Arc<Vec<Value>>) -> EvalOutcome {
+ // `from_shared` clones the `Arc`, not the opcode vector, so swapping programs is just a refcount bump.
+ let program = match Program::from_shared(bytecode) {
+ Ok(program) => program,
+ Err(error) => return classify_failure(error),
+ };
+ self.context.set_program(program);
+ run(&self.context)
+ }
+}
+
+/// Run `context` to completion, collapsing the VM result to an [`EvalOutcome`]. `unwrap_or(false)`
+/// mirrors the Node `?? false` coercion of a non-bool result.
+fn run(context: &ExecutionContext) -> EvalOutcome {
+ match sync_execute(context, false) {
+ Ok(result) => EvalOutcome::Matched(result.as_bool().unwrap_or(false)),
+ Err(failure) => classify_failure(failure.error),
+ }
+}
+
+/// One-shot evaluation building a fresh context (used by the parity test). `bytecode` must be
+/// `RETURN`-terminated, as the catalog loader leaves it.
pub fn evaluate_detailed(bytecode: &[Value], globals: Value) -> EvalOutcome {
- let mut with_return = Vec::with_capacity(bytecode.len() + 1);
- with_return.extend_from_slice(bytecode);
- with_return.push(Value::from(OP_RETURN));
-
- // PERF: `with_defaults` rebuilds the full STL (~26 closures + 2 HashMaps + the hog module
- // symbol table) on every call — once per conditionHash per event. Reuse is blocked by the
- // shared `hogvm` API: `NativeFunction` is `Box<dyn Fn>` (not `Clone`), `ExecutionContext`
- // owns its tables, and there is no program setter, so a thread_local context can't swap
- // programs in place without a shared-crate change. `with_globals` also takes ownership, so
- // the full globals JSON is cloned per condition. Flamegraph before optimizing.
- let program = match Program::new(with_return) {
+ let program = match Program::new(bytecode.to_vec()) {
Ok(program) => program,
Err(error) => return classify_failure(error),
};
- // Coercing comparisons (cross-type ordering + epoch temporal ordering/equality) match the
- // Python/TS/ClickHouse reference. Opt in here only — other consumers (e.g. cymbal) keep
- // strict comparisons.
let context = ExecutionContext::with_defaults(program)
.with_globals(globals)
.with_coercing_comparisons();
-
- match sync_execute(&context, false) {
- Ok(result) => EvalOutcome::Matched(result.as_bool().unwrap_or(false)),
- Err(failure) => classify_failure(failure.error),
- }
+ run(&context)
}
-/// Hot-path wrapper: coerces failures and non-bool results to `false`, emitting a per-class metric
-/// so a silently-failing cohort stays observable.
pub fn evaluate(bytecode: &[Value], globals: Value) -> bool {
- match evaluate_detailed(bytecode, globals) {
+ outcome_to_bool(evaluate_detailed(bytecode, globals))
+}
+
+/// Collapse an [`EvalOutcome`] to `bool`, emitting a per-class metric on failure.
+fn outcome_to_bool(outcome: EvalOutcome) -> bool {
+ match outcome {
EvalOutcome::Matched(matched) => matched,
EvalOutcome::UnknownFunction(name) => {
// `name` is bytecode-derived from user cohort filters; keep it out of the metric label
@@ -98,6 +140,8 @@ mod tests {
const OP_FALSE: i64 = 30;
const OP_INTEGER: i64 = 33;
const OP_STRING: i64 = 32;
+ // Fixtures terminate explicitly with RETURN, mirroring what the catalog loader stores.
+ const OP_RETURN: i64 = 38;
fn header() -> Vec<Value> {
vec![json!("_H"), json!(1)]
@@ -105,7 +149,7 @@ mod tests {
#[test]
fn true_literal_coerces_to_true() {
- let bc = [header(), vec![json!(OP_TRUE)]].concat();
+ let bc = [header(), vec![json!(OP_TRUE), json!(OP_RETURN)]].concat();
assert!(matches!(
evaluate_detailed(&bc, json!({})),
EvalOutcome::Matched(true)
@@ -114,7 +158,7 @@ mod tests {
#[test]
fn false_literal_coerces_to_false() {
- let bc = [header(), vec![json!(OP_FALSE)]].concat();
+ let bc = [header(), vec![json!(OP_FALSE), json!(OP_RETURN)]].concat();
assert!(matches!(
evaluate_detailed(&bc, json!({})),
EvalOutcome::Matched(false)
@@ -123,7 +167,11 @@ mod tests {
#[test]
fn non_boolean_result_coerces_to_false() {
- let bc = [header(), vec![json!(OP_INTEGER), json!(42)]].concat();
+ let bc = [
+ header(),
+ vec![json!(OP_INTEGER), json!(42), json!(OP_RETURN)],
+ ]
+ .concat();
assert!(matches!(
evaluate_detailed(&bc, json!({})),
EvalOutcome::Matched(false)
@@ -132,9 +180,7 @@ mod tests {
}
#[test]
- fn compiled_style_bytecode_without_trailing_return_still_evaluates() {
- // Guard the appended-RETURN bridge: cohort bytecode ends without RETURN, which the Rust VM
- // would reject with EndOfProgram; evaluate_detailed must append one.
+ fn compiled_style_bytecode_evaluates() {
let bc = [
header(),
vec![
@@ -145,6 +191,7 @@ mod tests {
json!(OP_GET_GLOBAL),
json!(1),
json!(OP_EQ),
+ json!(OP_RETURN),
],
]
.concat();
@@ -218,6 +265,7 @@ mod tests {
bc.extend_from_slice(&right);
bc.extend_from_slice(&left);
bc.push(json!(OP_LT));
+ bc.push(json!(OP_RETURN));
let globals =
|signup: Value| json!({ "person": { "properties": { "signup_date": signup } } });
@@ -226,6 +274,47 @@ mod tests {
assert!(!evaluate(&bc, json!({ "person": { "properties": {} } })));
}
+ #[test]
+ fn reused_evaluator_matches_a_fresh_context_per_eval() {
+ // Interleave programs and globals so a stale-globals or un-swapped-program leak would diverge
+ // from a fresh-context-per-eval baseline.
+ let email_eq = {
+ let mut bc = header();
+ bc.extend_from_slice(&[json!(OP_STRING), json!("[email protected]")]);
+ bc.extend_from_slice(&push_person_property("email"));
+ bc.extend_from_slice(&[json!(OP_EQ), json!(OP_RETURN)]);
+ bc
+ };
+ let num_gt = {
+ let mut bc = header();
+ bc.extend_from_slice(&[json!(OP_STRING), json!("10")]);
+ bc.extend_from_slice(&push_person_property("bc_num"));
+ bc.extend_from_slice(&[json!(OP_GT), json!(OP_RETURN)]);
+ bc
+ };
+ let g_match = json!({ "person": { "properties": { "email": "[email protected]", "bc_num": 20 } } });
+ let g_miss = json!({ "person": { "properties": { "email": "[email protected]", "bc_num": 5 } } });
+
+ let cases: [(&Vec<Value>, &Value); 5] = [
+ (&email_eq, &g_match),
+ (&num_gt, &g_match),
+ (&email_eq, &g_miss),
+ (&num_gt, &g_miss),
+ (&email_eq, &g_match),
+ ];
+
+ let mut evaluator = CohortEvaluator::new();
+ for (bytecode, globals) in cases {
+ evaluator.set_globals(globals.clone());
+ let reused = evaluator.evaluate(Arc::new(bytecode.clone()));
+ let fresh = evaluate(bytecode, globals.clone());
+ assert_eq!(
+ reused, fresh,
+ "reused evaluator diverged from a fresh per-eval context",
+ );
+ }
+ }
+
#[test]
fn numeric_gt_person_cohort_coerces_the_string_threshold() {
// Compiler emits the threshold as a string: `Gt(person.properties.bc_num, "10")`.
@@ -234,6 +323,7 @@ mod tests {
bc.extend_from_slice(&[json!(OP_STRING), json!("10")]);
bc.extend_from_slice(&push_person_property("bc_num"));
bc.push(json!(OP_GT));
+ bc.push(json!(OP_RETURN));
let globals = |num: Value| json!({ "person": { "properties": { "bc_num": num } } });
assert!(evaluate(&bc, globals(json!(20))));
diff --git a/rust/cohort-stream-processor/src/hogvm/mod.rs b/rust/cohort-stream-processor/src/hogvm/mod.rs
index 4bfaede60102..eb6446b57bec 100644
--- a/rust/cohort-stream-processor/src/hogvm/mod.rs
+++ b/rust/cohort-stream-processor/src/hogvm/mod.rs
@@ -4,5 +4,5 @@
mod executor;
mod globals;
-pub use executor::{evaluate, evaluate_detailed, EvalOutcome};
+pub use executor::{evaluate, evaluate_detailed, CohortEvaluator, EvalOutcome};
pub use globals::{build_behavioral_globals, build_person_property_globals, GlobalsError};
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 63505e07d6b0..8e2ccae7e86c 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -48,8 +48,12 @@ fn main() -> Result<()> {
let config = Config::init_from_env()
.context("Failed to load configuration from environment variables")?;
- let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
+ let mut runtime_builder = tokio::runtime::Builder::new_multi_thread();
+ runtime_builder.enable_all();
+ if config.tokio_worker_threads > 0 {
+ runtime_builder.worker_threads(config.tokio_worker_threads);
+ }
+ let runtime = runtime_builder
.build()
.context("Failed to build tokio runtime")?;
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index e1af8b761ae8..1ba867641f33 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -5,6 +5,7 @@
//! flipped. Transitions are surfaced only after the commit succeeds.
use std::collections::BTreeMap;
+use std::sync::Arc;
use metrics::counter;
use uuid::Uuid;
@@ -12,7 +13,7 @@ use uuid::Uuid;
use crate::consumers::events::CohortStreamEvent;
use crate::filters::reverse_index::TeamFilters;
use crate::filters::TeamId;
-use crate::hogvm::{build_behavioral_globals, build_person_property_globals, evaluate};
+use crate::hogvm::{build_behavioral_globals, build_person_property_globals, CohortEvaluator};
use crate::observability::metrics::{
STAGE1_ARGMAX_STALE, STAGE1_CONDITIONS_EVALUATED, STAGE1_PERSON_INDEX_APPENDS,
STAGE1_REPLAY_SKIPPED, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,
@@ -166,11 +167,9 @@ pub fn process_event(
None
};
- let applies = collect_applies(
- filters,
- behavioral_globals.as_ref(),
- person_globals.as_ref(),
- );
+ // One evaluator reused across the event's conditions: globals set once per kind, program per condition.
+ let mut evaluator = CohortEvaluator::new();
+ let applies = collect_applies(filters, &mut evaluator, behavioral_globals, person_globals);
if applies.is_empty() {
return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0));
}
@@ -312,18 +311,20 @@ pub(crate) fn schedule_deadline(state: &Stage1State) -> Option<i64> {
fn collect_applies(
filters: &TeamFilters,
- behavioral_globals: Option<&serde_json::Value>,
- person_globals: Option<&serde_json::Value>,
+ evaluator: &mut CohortEvaluator,
+ behavioral_globals: Option<serde_json::Value>,
+ person_globals: Option<serde_json::Value>,
) -> Vec<Apply> {
let mut applies = Vec::new();
if let Some(globals) = behavioral_globals {
+ evaluator.set_globals(globals);
for &hash in &filters.behavioral_conditions {
let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
continue;
};
counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "behavioral").increment(1);
- if !evaluate(bytecode, globals.clone()) {
+ if !evaluator.evaluate(Arc::clone(bytecode)) {
continue;
}
let Some(lsks) = filters.by_condition_to_lsk.get(&hash) else {
@@ -352,12 +353,13 @@ fn collect_applies(
}
if let Some(globals) = person_globals {
+ evaluator.set_globals(globals);
for &hash in &filters.person_property_conditions {
let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
continue;
};
counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);
- let matches = evaluate(bytecode, globals.clone());
+ let matches = evaluator.evaluate(Arc::clone(bytecode));
let lsk = LeafStateKey::for_person_property(&hash);
match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
Some(StateVariant::PersonProperty) => {
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 1df5e0ab921d..343f1b5c3b56 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -7,7 +7,7 @@
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::Arc;
-use std::time::Instant;
+use std::time::{Duration, Instant};
use metrics::{counter, histogram};
use tokio::sync::mpsc;
@@ -56,6 +56,11 @@ const MAX_SWEEP_KEYS_PER_PASS: usize = 10_000;
const REBUILD_SCAN_PAGE: usize = 10_000;
+/// Cooperative-yield cadence inside the worker fold. `handle_event` is synchronous, so a backlog of
+/// CPU-bound events would hold the runtime thread, starving the commit task and consume loop. A
+/// wall-clock interval adapts to per-event cost across catalogs of different sizes.
+const WORKER_YIELD_INTERVAL: Duration = Duration::from_millis(5);
+
pub struct Stage1Worker {
partition_id: u16,
handle: JoinHandle<()>,
@@ -116,12 +121,14 @@ async fn run_worker(
let mut queue = EvictionQueue::<Stage1Key>::new();
// No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
if durable_restore {
- rebuild_eviction_queue(partition_id, &store, &mut queue);
+ rebuild_eviction_queue(partition_id, &store, &mut queue).await;
}
// In-memory resume cursors; loss on rebalance is benign (GC re-scans from the start).
let mut gc_cursor = MergeGcCursor::default();
let mut stage2_gc_cursor = Stage2GcCursor::default();
+ // Persists across batches so a stream of buffered batches still yields on the wall-clock interval.
+ let mut last_yield = Instant::now();
while let Some(batch) = receiver.recv().await {
let last_updated = now_last_updated();
let mut buffer = OutputBuffer::new();
@@ -269,6 +276,11 @@ async fn run_worker(
}
}
}
+
+ if last_yield.elapsed() >= WORKER_YIELD_INTERVAL {
+ tokio::task::yield_now().await;
+ last_yield = Instant::now();
+ }
}
if held {
@@ -771,7 +783,7 @@ async fn handle_sweep(
/// stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX` deadlines
/// (permanent). Corrupt records are counted and skipped — the event path re-derives them. A scan error
/// stops early; new events reschedule any missing keys.
-fn rebuild_eviction_queue(
+async fn rebuild_eviction_queue(
partition_id: u16,
store: &CohortStore,
queue: &mut EvictionQueue<Stage1Key>,
@@ -808,6 +820,9 @@ fn rebuild_eviction_queue(
if page_len < REBUILD_SCAN_PAGE {
break;
}
+ // Workers re-seed concurrently on restart; yield between pages so the boot scan doesn't
+ // saturate the runtime before the consume loop starts.
+ tokio::task::yield_now().await;
}
if rebuilt > 0 {
counter!(EVICTION_QUEUE_REBUILT_KEYS_TOTAL, "partition" => partition_id.to_string())
diff --git a/rust/cohort-stream-processor/tests/filter_catalog.rs b/rust/cohort-stream-processor/tests/filter_catalog.rs
index b0f28984c0c1..a35c48af2791 100644
--- a/rust/cohort-stream-processor/tests/filter_catalog.rs
+++ b/rust/cohort-stream-processor/tests/filter_catalog.rs
@@ -27,6 +27,16 @@ fn behavioral_bytecode() -> Value {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
+/// HogVM `RETURN` opcode, appended to stored bytecode by the catalog loader.
+const OP_RETURN: i64 = 38;
+
+/// The stored form of [`behavioral_bytecode`]: the loader appends a trailing `RETURN` (opcode 38).
+fn behavioral_bytecode_loaded() -> Vec<Value> {
+ let mut bc = behavioral_bytecode().as_array().unwrap().clone();
+ bc.push(json!(OP_RETURN));
+ bc
+}
+
/// The conditionHash encodes the event matcher, not the `time_value` window — same hash, any window.
fn behavioral_performed_event(time_value: i64) -> Value {
json!({
@@ -153,7 +163,7 @@ fn bytecode_is_captured_and_deduped_by_condition_hash() {
assert_eq!(team.by_condition_to_bytecode.len(), 2);
assert_eq!(
team.by_condition_to_bytecode[&BEHAVIORAL_HASH].as_ref(),
- behavioral_bytecode().as_array().unwrap(),
+ &behavioral_bytecode_loaded(),
);
assert!(team.by_condition_to_bytecode.contains_key(&PERSON_HASH));
}
diff --git a/rust/cohort-stream-processor/tests/hogvm_parity.rs b/rust/cohort-stream-processor/tests/hogvm_parity.rs
index 7fba8d4e74ec..2c57ad0b2d93 100644
--- a/rust/cohort-stream-processor/tests/hogvm_parity.rs
+++ b/rust/cohort-stream-processor/tests/hogvm_parity.rs
@@ -16,6 +16,10 @@ use std::path::{Path, PathBuf};
use cohort_stream_processor::hogvm::{evaluate_detailed, EvalOutcome};
use serde_json::Value;
+/// HogVM `RETURN`. Fixtures store compiled bytecode without it; append it so the parity oracle runs
+/// the same RETURN-terminated shape the hot path does.
+const OP_RETURN: i64 = 38;
+
/// A missing directory yields no fixtures (optional corpus); any other read/parse failure panics.
fn fixtures_in(dir: &Path) -> Vec<(PathBuf, Value)> {
let Ok(entries) = fs::read_dir(dir) else {
@@ -64,11 +68,13 @@ fn rust_executor_matches_python_oracle() {
let bytecode = fixture["bytecode"]
.as_array()
.unwrap_or_else(|| panic!("fixture {path:?} `bytecode` must be an array"));
+ let mut bytecode = bytecode.clone();
+ bytecode.push(Value::from(OP_RETURN));
let globals = fixture["globals"].clone();
// `unwrap_or(false)` mirrors the Node `?? false` coercion.
let expected = fixture["expected_result"].as_bool().unwrap_or(false);
- let actual = match evaluate_detailed(bytecode, globals) {
+ let actual = match evaluate_detailed(&bytecode, globals) {
EvalOutcome::Matched(matched) => matched,
other => panic!("fixture `{name}` ({path:?}) did not evaluate cleanly: {other:?}"),
};
diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rs
index 875f08696553..4975f2185a77 100644
--- a/rust/common/hogvm/src/context.rs
+++ b/rust/common/hogvm/src/context.rs
@@ -1,5 +1,7 @@
+use once_cell::sync::Lazy;
use serde_json::{json, Value as JsonValue};
use std::collections::HashMap;
+use std::sync::Arc;
use crate::{
error::VmError,
@@ -9,6 +11,26 @@ use crate::{
HogLiteral, HogValue,
};
+/// Default native-function and symbol tables, built once from the process-static STL and shared via
+/// `Arc` by every [`ExecutionContext::with_defaults`] so the maps aren't rebuilt per context.
+static DEFAULT_NATIVE_FNS: Lazy<Arc<HashMap<String, NativeFunction>>> =
+ Lazy::new(|| Arc::new(stl_map()));
+static DEFAULT_SYMBOL_TABLE: Lazy<Arc<HashMap<Symbol, ExportedFunction>>> =
+ Lazy::new(|| Arc::new(flatten_modules(&hog_stl_map())));
+
+/// Flatten imported modules into the symbol table the VM looks up by `Symbol{module, name}`. The
+/// module name is the `module` half, matching the `Symbol::new("stl", …)` the VM builds at
+/// `CallGlobal` (see `vm.rs`).
+fn flatten_modules(modules: &HashMap<String, Module>) -> HashMap<Symbol, ExportedFunction> {
+ let mut table = HashMap::new();
+ for (name, module) in modules.iter() {
+ for (fn_name, function) in module.functions().iter() {
+ table.insert(Symbol::new(name, fn_name), function.clone());
+ }
+ }
+ table
+}
+
/// The read-only context for the virtual machine.
pub struct ExecutionContext {
program: Program,
@@ -24,8 +46,10 @@ pub struct ExecutionContext {
/// by epoch, and `Eq` compare two temporals by epoch — the ClickHouse/Python-TS-aligned semantics
/// the realtime-cohort evaluator needs. Set via [`ExecutionContext::with_coercing_comparisons`].
pub(crate) coerce_comparisons: bool,
- native_fns: HashMap<String, NativeFunction>,
- symbol_table: HashMap<Symbol, ExportedFunction>, // Flattened symbol table of all imported hog modules
+ // `Arc`-shared so cloning a default context is a refcount bump, not a deep copy; mutators
+ // copy-on-write via `Arc::make_mut`.
+ native_fns: Arc<HashMap<String, NativeFunction>>,
+ symbol_table: Arc<HashMap<Symbol, ExportedFunction>>, // Flattened symbol table of all imported hog modules
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
@@ -51,37 +75,37 @@ impl ExecutionContext {
max_heap_size,
max_steps,
coerce_comparisons: false,
- native_fns,
- symbol_table: HashMap::new(),
+ native_fns: Arc::new(native_fns),
+ symbol_table: Arc::new(flatten_modules(&modules)),
}
- .with_modules(&modules)
}
pub fn with_defaults(bytecode: Program) -> Self {
- // TODO - these values are basically randomly chosen
- Self::new(
- bytecode,
- json!({}),
- 128,
- 1024 * 1024,
- 10_000,
- stl_map(),
- hog_stl_map(),
- )
+ // TODO - these limits are basically randomly chosen
+ Self {
+ program: bytecode,
+ globals: json!({}),
+ max_stack_depth: 128,
+ max_heap_size: 1024 * 1024,
+ max_steps: 10_000,
+ coerce_comparisons: false,
+ native_fns: DEFAULT_NATIVE_FNS.clone(),
+ symbol_table: DEFAULT_SYMBOL_TABLE.clone(),
+ }
}
pub fn with_ext_fn(mut self, name: String, func: NativeFunction) -> Self {
- self.native_fns.insert(name, func);
+ Arc::make_mut(&mut self.native_fns).insert(name, func);
self
}
pub fn with_ext_fns(mut self, fns: HashMap<String, NativeFunction>) -> Self {
- self.native_fns.extend(fns);
+ Arc::make_mut(&mut self.native_fns).extend(fns);
self
}
pub fn set_fns(mut self, fns: HashMap<String, NativeFunction>) -> Self {
- self.native_fns = fns;
+ self.native_fns = Arc::new(fns);
self
}
@@ -90,6 +114,16 @@ impl ExecutionContext {
self
}
+ /// Swap globals in place (no clone) so one context can be reused across evaluations sharing them.
+ pub fn set_globals(&mut self, globals: JsonValue) {
+ self.globals = globals;
+ }
+
+ /// Swap the program in place to reuse one context across many programs (e.g. catalog conditions).
+ pub fn set_program(&mut self, program: Program) {
+ self.program = program;
+ }
+
/// Opt into coercing comparison semantics (cross-type ordering coercion + epoch ordering/equality
/// of temporals). Off by default; only the realtime-cohort evaluator opts in, so existing
/// consumers like `cymbal` keep the legacy strict behavior. See [`Self::coerce_comparisons`].
@@ -114,17 +148,14 @@ impl ExecutionContext {
}
pub fn with_modules(mut self, modules: &HashMap<String, Module>) -> Self {
- self.symbol_table.clear();
- for (name, module) in modules.iter() {
- self = self.add_module(name.clone(), module);
- }
+ self.symbol_table = Arc::new(flatten_modules(modules));
self
}
pub fn add_module(mut self, name: String, module: &Module) -> Self {
+ let table = Arc::make_mut(&mut self.symbol_table);
for (fn_name, function) in module.functions().iter() {
- self.symbol_table
- .insert(Symbol::new(&name, fn_name), function.clone());
+ table.insert(Symbol::new(&name, fn_name), function.clone());
}
self
}
diff --git a/rust/common/hogvm/src/program.rs b/rust/common/hogvm/src/program.rs
index 374d2bda154a..a5aa7dbcc5ec 100644
--- a/rust/common/hogvm/src/program.rs
+++ b/rust/common/hogvm/src/program.rs
@@ -1,12 +1,14 @@
use std::collections::HashMap;
+use std::sync::Arc;
use serde_json::{Number, Value as JsonValue};
use crate::VmError;
-// A top-level hog program - functionally the body of a "main" function, if hog had such a thing
+// A top-level hog program - functionally the body of a "main" function, if hog had such a thing.
+// `bytecode` is `Arc`-shared so building a program from shared bytecode is a refcount bump.
pub struct Program {
- bytecode: Vec<JsonValue>,
+ bytecode: Arc<Vec<JsonValue>>,
version: u64,
program_start_offset: usize,
}
@@ -25,6 +27,12 @@ pub struct ExportedFunction {
impl Program {
pub fn new(bytecode: Vec<JsonValue>) -> Result<Self, VmError> {
+ Self::from_shared(Arc::new(bytecode))
+ }
+
+ /// Build a program from `Arc`-shared bytecode without copying it — for bytecode held in a shared
+ /// catalog and evaluated repeatedly.
+ pub fn from_shared(bytecode: Arc<Vec<JsonValue>>) -> Result<Self, VmError> {
if bytecode.is_empty() {
return Err(VmError::InvalidBytecode(
"Missing bytecode marker at position 0".to_string(),
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 0dd807c0d80e..b9a84ce778b6 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -353,7 +353,9 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
let Some(res) = res else {
return Ok(HogLiteral::Null.into());
};
- construct_free_standing(res, 0)
+ // `res` borrows into the local `json`; clone the extracted subtree for the owned
+ // value `construct_free_standing` needs.
+ construct_free_standing(res.clone(), 0)
})),
),
// Wrapped in `err_to_null` so an unparseable input becomes `Null`, letting a leaf's
diff --git a/rust/common/hogvm/src/util.rs b/rust/common/hogvm/src/util.rs
index 9603923ffcf4..f7d86ad8f0eb 100644
--- a/rust/common/hogvm/src/util.rs
+++ b/rust/common/hogvm/src/util.rs
@@ -113,17 +113,19 @@ fn like_to_regex(pattern: &str) -> String {
result
}
-pub fn get_json_nested(
- haystack: &Value,
+/// Walk `chain` into `haystack`, returning a borrow tied to `haystack` (a caller needing an owned
+/// value clones only the final subtree). On the hot path of every `GET_GLOBAL`.
+pub fn get_json_nested<'h>(
+ haystack: &'h Value,
mut chain: &[HogValue],
vm: &HogVM,
-) -> Result<Option<Value>, VmError> {
+) -> Result<Option<&'h Value>, VmError> {
let mut current = Some(haystack);
while let Some(val) = current {
if chain.is_empty() {
// We found a value pointed to by the last element in the chain
- return Ok(Some(val.clone()));
+ return Ok(Some(val));
}
let next_key = chain.first().unwrap().deref(&vm.heap)?;
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 97893a278ca6..89fcf583d82f 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -119,12 +119,15 @@ impl<'a> HogVM<'a> {
return Err(VmError::UnknownGlobal("".to_string()));
}
- if let Some(found) = get_json_nested(&self.context.globals, &chain, self)? {
+ // Copy out the `Copy` `&ExecutionContext` so the `found` borrow is tied to it, not to
+ // `self` — leaving `self` free for the `&mut self` `json_to_hog` call below.
+ let context = self.context;
+ if let Some(found) = get_json_nested(&context.globals, &chain, self)? {
let val = self.json_to_hog(found)?;
self.push_stack(val)?;
} else if let Ok(closure) = self.get_fn_reference(&chain) {
self.push_stack(closure)?;
- } else if get_json_nested(&self.context.globals, &chain[..1], self)?.is_some() {
+ } else if get_json_nested(&context.globals, &chain[..1], self)?.is_some() {
// If the first element of the chain is a global, push null onto the stack, e.g.
// if a program is looking for "properties.blah", and "properties" exists, but
// "blah" doesn't, push null onto the stack.
@@ -855,22 +858,24 @@ impl<'a> HogVM<'a> {
// This is a function on the VM, rather than being standalone, because hog values don't really
// exist outside of the context of a VM (and specifically a heap). It could be a function on the
// heap itself, though.
- pub fn json_to_hog(&mut self, json: JsonValue) -> Result<HogValue, VmError> {
+ pub fn json_to_hog(&mut self, json: &JsonValue) -> Result<HogValue, VmError> {
self.json_to_hog_impl(json, 0)
}
- fn json_to_hog_impl(&mut self, current: JsonValue, depth: usize) -> Result<HogValue, VmError> {
+ fn json_to_hog_impl(&mut self, current: &JsonValue, depth: usize) -> Result<HogValue, VmError> {
if depth > MAX_JSON_SERDE_DEPTH {
return Err(VmError::OutOfResource(
"json->hog deserialization depth".to_string(),
));
};
+ // Clone only the scalar leaves (numbers/strings); containers are walked by reference and
+ // rebuilt onto the heap.
match current {
JsonValue::Null => Ok(HogLiteral::Null.into()),
- JsonValue::Bool(b) => Ok(HogLiteral::Boolean(b).into()),
- JsonValue::Number(n) => Ok(HogLiteral::Number(n.into()).into()),
- JsonValue::String(s) => Ok(HogLiteral::String(s).into()),
+ JsonValue::Bool(b) => Ok(HogLiteral::Boolean(*b).into()),
+ JsonValue::Number(n) => Ok(HogLiteral::Number(n.clone().into()).into()),
+ JsonValue::String(s) => Ok(HogLiteral::String(s.clone()).into()),
JsonValue::Array(arr) => {
let mut values = Vec::new();
for value in arr {
@@ -883,7 +888,7 @@ impl<'a> HogVM<'a> {
JsonValue::Object(obj) => {
let mut map = HashMap::new();
for (key, value) in obj {
- map.insert(key, self.json_to_hog_impl(value, depth + 1)?);
+ map.insert(key.clone(), self.json_to_hog_impl(value, depth + 1)?);
}
let to_emplace = HogLiteral::Object(map);
let ptr = self.heap.emplace(to_emplace)?;