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): add static bytecode analysis for behavioral conditions (#91390)

Matheus Batista9ccd3ff3df07
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index d0163dde8da1..35052c548999 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2591,6 +2591,7 @@ dependencies = [
"hogvm",
"metrics",
"petgraph 0.8.3",
+ "proptest",
"serde",
"serde_json",
"sha2 0.10.9",
diff --git a/rust/cohort-core/Cargo.toml b/rust/cohort-core/Cargo.toml
index 7fe25c3cb9c8..7758ed75aa13 100644
--- a/rust/cohort-core/Cargo.toml
+++ b/rust/cohort-core/Cargo.toml
@@ -20,3 +20,6 @@ sqlx = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
+
+[dev-dependencies]
+proptest = "1"
diff --git a/rust/cohort-core/src/hogvm/analysis/decode.rs b/rust/cohort-core/src/hogvm/analysis/decode.rs
new file mode 100644
index 000000000000..8975acb95937
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/analysis/decode.rs
@@ -0,0 +1,779 @@
+//! Turns a bytecode array into typed instructions, consuming each opcode's immediates exactly as
+//! `hogvm::HogVM::step` does.
+//!
+//! This module holds no policy about which instructions an analysis can handle. It answers two
+//! questions: where does each instruction start and end, and where does each branch land. Getting
+//! the first wrong would misread the following tokens as opcodes, so the immediate counts here must
+//! track `vm.rs` and nothing else. Whether a landing site is *legal* is the analysis layer's call,
+//! because only that layer knows where instructions begin.
+
+use std::sync::Arc;
+
+use hogvm::Operation;
+use serde_json::Value;
+
+/// A position in the raw token array. Jump offsets are expressed in these, and the VM resolves them
+/// against a body-relative instruction pointer — which differs from an index into the full array by
+/// the constant header length, so adding an offset gives the same landing site either way.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub(super) struct TokenIndex(pub(super) usize);
+
+/// A position in the decoded instruction list.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub(super) struct InstrIndex(pub(super) usize);
+
+/// One decoded instruction and where it starts, so a branch target can be matched against the
+/// instruction boundaries.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct Instr {
+ pub(super) start: TokenIndex,
+ pub(super) kind: InstrKind,
+}
+
+/// The instruction itself, grouped by the shape of its immediates rather than by what it does. The
+/// [`Operation`] is always carried, so the interpreter still dispatches on the exact opcode.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) enum InstrKind {
+ /// No immediates: comparisons, arithmetic, `NOT`, `POP`, `RETURN`, property reads, `THROW`,
+ /// `POP_TRY`, `CLOSE_UPVALUE`, the cohort opcodes, and the bare constants.
+ Bare(Operation),
+ /// A single count immediate: `GET_GLOBAL`, `AND`, `OR`, `DICT`, `ARRAY`, `TUPLE`, `CALL_LOCAL`,
+ /// the local slots, and the upvalue slots.
+ Counted(Operation, usize),
+ /// A jump, with its offset resolved to the token it lands on. `None` when the offset resolves
+ /// outside the addressable range, which is refused on visit rather than at decode: an offset no
+ /// path follows must not fail a program that never reaches the opcode.
+ Branch {
+ op: Operation,
+ target: Option<TokenIndex>,
+ },
+ /// `TRY`. It carries a jump offset like the branches, but the interpreter refuses it, so no
+ /// landing site is resolved: an offset nothing will follow must not be able to fail a program
+ /// that never reaches the opcode.
+ Try,
+ /// `STRING` and the literal it pushes. The literal is the only immediate the analysis reads,
+ /// because a global path is built from them. `Arc<str>` because the interpreter carries these
+ /// on abstract stacks it copies at every branch merge, and copying the bytes there is what
+ /// turns one long literal into an allocation proportional to the program length.
+ String(Arc<str>),
+ /// `INTEGER` or `FLOAT`. The value is not retained: the abstract domain cannot name a number,
+ /// so nothing downstream could use it.
+ Number(Operation),
+ /// `CALL_GLOBAL`, with the callee name and its argument count.
+ CallGlobal { name: String, argc: usize },
+ /// `CALLABLE`, with the span of the body tokens it skips. The interpreter skips them exactly as
+ /// the VM does by advancing past `body_length`; the span is kept so a caller that needs to look
+ /// inside — the standard-library guard — can decode them in place.
+ Callable { body: TokenSpan },
+ /// `CLOSURE`, with its capture pairs consumed.
+ Closure,
+}
+
+/// A half-open token range, in absolute positions so a nested decode resolves jumps the same way
+/// the enclosing one does.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) struct TokenSpan {
+ pub(super) start: TokenIndex,
+ pub(super) end: TokenIndex,
+}
+
+/// A decoded program: its instructions, and the token one past its last, which is where a jump off
+/// the end lands.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct Decoded {
+ pub(super) instrs: Vec<Instr>,
+ pub(super) body_end: TokenIndex,
+}
+
+/// Why a bytecode array could not be split into instructions.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum DecodeError {
+ #[error("bytecode does not start with the `_H` marker")]
+ MissingHeader,
+ #[error("bytecode version marker is not an unsigned integer")]
+ MalformedVersion,
+ #[error("token at {ip} is not an opcode")]
+ NotAnOpcode { ip: usize },
+ #[error("{op:?} at {ip} runs past the end of the bytecode")]
+ TruncatedImmediates { ip: usize, op: Operation },
+ #[error("{op:?} at {ip} has a malformed immediate")]
+ MalformedImmediate { ip: usize, op: Operation },
+}
+
+impl DecodeError {
+ /// Which opcode's immediates could not be read, when the failure names one.
+ ///
+ /// Exhaustive rather than defaulted, so a new variant carrying an [`Operation`] has to decide
+ /// whether it surfaces here. Losing the opcode silently is what makes a decoder-versus-VM drift
+ /// read as one anonymous bucket, which is the case this label exists for.
+ pub fn op(&self) -> Option<Operation> {
+ match self {
+ Self::TruncatedImmediates { op, .. } | Self::MalformedImmediate { op, .. } => Some(*op),
+ Self::MissingHeader | Self::MalformedVersion | Self::NotAnOpcode { .. } => None,
+ }
+ }
+}
+
+/// Split `bytecode` into instructions.
+///
+/// The header handling mirrors `hogvm::Program::from_shared` exactly, version ambiguity included: a
+/// pre-version program whose first opcode happens to be a number has that opcode read as its
+/// version. The VM reads it the same way, so an analysis that disagreed would be describing a
+/// program the VM never runs. That is also why the version has to be an unsigned integer here: the
+/// VM takes it through `as_u64`, so a negative or fractional version is a program it refuses to
+/// load, and accepting it would classify bytecode that never runs.
+pub(super) fn decode(bytecode: &[Value]) -> Result<Decoded, DecodeError> {
+ if bytecode.first().and_then(Value::as_str) != Some("_H") {
+ return Err(DecodeError::MissingHeader);
+ }
+ let body_start = match bytecode.get(1) {
+ None => 1,
+ Some(Value::Number(version)) if version.as_u64().is_some() => 2,
+ Some(_) => return Err(DecodeError::MalformedVersion),
+ };
+ decode_span(
+ bytecode,
+ TokenSpan {
+ start: TokenIndex(body_start),
+ end: TokenIndex(bytecode.len()),
+ },
+ )
+}
+
+/// Decode one span of an already-headered array — a `CALLABLE` body, say. Positions stay absolute,
+/// so a jump inside the span resolves to the same token the VM would reach.
+pub(super) fn decode_span(tokens: &[Value], span: TokenSpan) -> Result<Decoded, DecodeError> {
+ let mut cursor = Cursor {
+ tokens,
+ ip: span.start.0,
+ end: span.end.0,
+ };
+ let mut instrs = Vec::new();
+ while let Some(instr) = cursor.next_instr()? {
+ instrs.push(instr);
+ }
+ Ok(Decoded {
+ instrs,
+ body_end: span.end,
+ })
+}
+
+struct Cursor<'a> {
+ tokens: &'a [Value],
+ ip: usize,
+ end: usize,
+}
+
+impl<'a> Cursor<'a> {
+ fn next_instr(&mut self) -> Result<Option<Instr>, DecodeError> {
+ if self.ip >= self.end {
+ return Ok(None);
+ }
+ let op_ip = self.ip;
+ let token = &self.tokens[op_ip];
+ let op = Operation::try_from(token.clone())
+ .map_err(|_| DecodeError::NotAnOpcode { ip: op_ip })?;
+ self.ip += 1;
+ Ok(Some(Instr {
+ start: TokenIndex(op_ip),
+ kind: self.kind_for(op, op_ip)?,
+ }))
+ }
+
+ /// The immediate table, one arm per opcode. Exhaustive on purpose: a new opcode in the VM must
+ /// not silently inherit "no immediates", which would misalign every instruction after it.
+ fn kind_for(&mut self, op: Operation, op_ip: usize) -> Result<InstrKind, DecodeError> {
+ match op {
+ Operation::String => Ok(InstrKind::String(Arc::from(
+ self.take_string(op, op_ip)?.as_str(),
+ ))),
+ Operation::Integer | Operation::Float => {
+ self.take_token(op, op_ip)?;
+ Ok(InstrKind::Number(op))
+ }
+ Operation::GetGlobal
+ | Operation::And
+ | Operation::Or
+ | Operation::Dict
+ | Operation::Array
+ | Operation::Tuple
+ | Operation::CallLocal
+ | Operation::GetLocal
+ | Operation::SetLocal
+ | Operation::GetUpvalue
+ | Operation::SetUpvalue => Ok(InstrKind::Counted(op, self.take_count(op, op_ip)?)),
+ Operation::Jump | Operation::JumpIfFalse | Operation::JumpIfStackNotNull => {
+ let target = self.take_target(op, op_ip)?;
+ Ok(InstrKind::Branch { op, target })
+ }
+ // `TRY`'s immediate is consumed so the instructions after it decode at the right
+ // offsets, but its offset is deliberately left unresolved — see [`InstrKind::Try`].
+ Operation::Try => {
+ self.take_i64(op, op_ip)?;
+ Ok(InstrKind::Try)
+ }
+ Operation::CallGlobal => {
+ let name = self.take_string(op, op_ip)?;
+ let argc = self.take_count(op, op_ip)?;
+ Ok(InstrKind::CallGlobal { name, argc })
+ }
+ Operation::Callable => {
+ self.take_string(op, op_ip)?;
+ self.take_count(op, op_ip)?;
+ self.take_count(op, op_ip)?;
+ let body_length = self.take_count(op, op_ip)?;
+ let start = TokenIndex(self.ip);
+ self.skip(body_length, op, op_ip)?;
+ Ok(InstrKind::Callable {
+ body: TokenSpan {
+ start,
+ end: TokenIndex(self.ip),
+ },
+ })
+ }
+ Operation::Closure => {
+ let captures = self.take_count(op, op_ip)?;
+ let pairs = captures.checked_mul(2).ok_or(malformed(op, op_ip))?;
+ self.skip(pairs, op, op_ip)?;
+ Ok(InstrKind::Closure)
+ }
+ // `DECLARE_FN` reaches the VM only to be refused, so it never consumes its immediates
+ // there and there is no arity to copy. Reading it as bare keeps this decoder aligned
+ // with the VM; the interpreter refuses the opcode either way.
+ Operation::DeclareFn
+ | Operation::Not
+ | Operation::Plus
+ | Operation::Minus
+ | Operation::Mult
+ | Operation::Div
+ | Operation::Mod
+ | Operation::Eq
+ | Operation::NotEq
+ | Operation::Gt
+ | Operation::GtEq
+ | Operation::Lt
+ | Operation::LtEq
+ | Operation::Like
+ | Operation::Ilike
+ | Operation::NotLike
+ | Operation::NotIlike
+ | Operation::In
+ | Operation::NotIn
+ | Operation::Regex
+ | Operation::NotRegex
+ | Operation::Iregex
+ | Operation::NotIregex
+ | Operation::InCohort
+ | Operation::NotInCohort
+ | Operation::True
+ | Operation::False
+ | Operation::Null
+ | Operation::Pop
+ | Operation::Return
+ | Operation::GetProperty
+ | Operation::SetProperty
+ | Operation::GetPropertyNullish
+ | Operation::Throw
+ | Operation::PopTry
+ | Operation::CloseUpvalue => Ok(InstrKind::Bare(op)),
+ }
+ }
+
+ fn take_token(&mut self, op: Operation, op_ip: usize) -> Result<&'a Value, DecodeError> {
+ if self.ip >= self.end {
+ return Err(truncated(op, op_ip));
+ }
+ let token = &self.tokens[self.ip];
+ self.ip += 1;
+ Ok(token)
+ }
+
+ fn take_string(&mut self, op: Operation, op_ip: usize) -> Result<String, DecodeError> {
+ self.take_token(op, op_ip)?
+ .as_str()
+ .map(str::to_owned)
+ .ok_or(malformed(op, op_ip))
+ }
+
+ /// Read a count immediate, bounded by the token count.
+ ///
+ /// Every count in the instruction set is either a span of tokens to skip or a number of stack
+ /// values to consume, and the stack can never hold more values than the program has tokens to
+ /// push them with. So no honest count exceeds `tokens.len()`, and refusing the rest here keeps
+ /// a hostile catalog row from reaching a `Vec::with_capacity` downstream — where a `u64::MAX`
+ /// is a capacity-overflow panic and a merely huge value is an allocation abort, neither of
+ /// which the fail-closed contract can absorb.
+ fn take_count(&mut self, op: Operation, op_ip: usize) -> Result<usize, DecodeError> {
+ self.take_token(op, op_ip)?
+ .as_u64()
+ .and_then(|count| usize::try_from(count).ok())
+ .filter(|count| *count <= self.tokens.len())
+ .ok_or(malformed(op, op_ip))
+ }
+
+ fn take_i64(&mut self, op: Operation, op_ip: usize) -> Result<i64, DecodeError> {
+ self.take_token(op, op_ip)?
+ .as_i64()
+ .ok_or(malformed(op, op_ip))
+ }
+
+ /// Resolve a jump offset against the instruction pointer the VM would hold: one past the
+ /// offset immediate.
+ ///
+ /// An offset that resolves outside the addressable range yields `None` rather than an error.
+ /// Whether a landing site is usable is the analysis layer's question, and it asks it on visit,
+ /// so a dead jump cannot fail the decode of instructions a path does reach.
+ fn take_target(
+ &mut self,
+ op: Operation,
+ op_ip: usize,
+ ) -> Result<Option<TokenIndex>, DecodeError> {
+ let offset = self.take_i64(op, op_ip)?;
+ Ok(i64::try_from(self.ip)
+ .ok()
+ .and_then(|ip| ip.checked_add(offset))
+ .and_then(|target| usize::try_from(target).ok())
+ .map(TokenIndex))
+ }
+
+ fn skip(&mut self, count: usize, op: Operation, op_ip: usize) -> Result<(), DecodeError> {
+ let end = self.ip.checked_add(count).ok_or(malformed(op, op_ip))?;
+ if end > self.end {
+ return Err(truncated(op, op_ip));
+ }
+ self.ip = end;
+ Ok(())
+ }
+}
+
+fn truncated(op: Operation, ip: usize) -> DecodeError {
+ DecodeError::TruncatedImmediates { ip, op }
+}
+
+fn malformed(op: Operation, ip: usize) -> DecodeError {
+ DecodeError::MalformedImmediate { ip, op }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ /// The `["_H", <version>]` header [`body`] prepends, so a token position in a case is readable
+ /// as an offset into that case's own tokens.
+ const HEADER_LEN: usize = 2;
+
+ fn body(tokens: Vec<Value>) -> Vec<Value> {
+ let mut bytecode = vec![json!("_H"), json!(1)];
+ bytecode.extend(tokens);
+ bytecode
+ }
+
+ fn kinds(bytecode: &[Value]) -> Result<Vec<InstrKind>, DecodeError> {
+ Ok(decode(bytecode)?
+ .instrs
+ .into_iter()
+ .map(|instr| instr.kind)
+ .collect())
+ }
+
+ /// One case per immediate arity class. A wrong count here shifts every later instruction, so
+ /// the decoded sequence is asserted whole rather than by length.
+ #[test]
+ fn each_arity_class_consumes_exactly_its_immediates() {
+ let cases: Vec<(Vec<Value>, Vec<InstrKind>)> = vec![
+ (vec![json!(11)], vec![InstrKind::Bare(Operation::Eq)]),
+ (
+ vec![json!(32), json!("x"), json!(35)],
+ vec![
+ InstrKind::String(Arc::from("x")),
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ vec![json!(33), json!(7), json!(34), json!(1.5), json!(35)],
+ vec![
+ InstrKind::Number(Operation::Integer),
+ InstrKind::Number(Operation::Float),
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ vec![json!(1), json!(2), json!(35)],
+ vec![
+ InstrKind::Counted(Operation::GetGlobal, 2),
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ // JUMP at tokens 2-3 lands one token past its immediate, minus four: token 0.
+ vec![json!(39), json!(-4), json!(35)],
+ vec![
+ InstrKind::Branch {
+ op: Operation::Jump,
+ target: Some(TokenIndex(0)),
+ },
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ vec![json!(50), json!(2), json!(35)],
+ vec![InstrKind::Try, InstrKind::Bare(Operation::Pop)],
+ ),
+ (
+ vec![json!(2), json!("toString"), json!(1), json!(35)],
+ vec![
+ InstrKind::CallGlobal {
+ name: "toString".to_owned(),
+ argc: 1,
+ },
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ // CALLABLE skips its two body tokens the way the VM does, so POP decodes after it.
+ vec![
+ json!(52),
+ json!("f"),
+ json!(0),
+ json!(0),
+ json!(2),
+ json!(29),
+ json!(38),
+ json!(35),
+ ],
+ vec![
+ InstrKind::Callable {
+ body: TokenSpan {
+ start: TokenIndex(7),
+ end: TokenIndex(9),
+ },
+ },
+ InstrKind::Bare(Operation::Pop),
+ ],
+ ),
+ (
+ // CLOSURE with two captures consumes four capture tokens.
+ vec![
+ json!(53),
+ json!(2),
+ json!(true),
+ json!(0),
+ json!(false),
+ json!(1),
+ json!(35),
+ ],
+ vec![InstrKind::Closure, InstrKind::Bare(Operation::Pop)],
+ ),
+ ];
+ for (tokens, expected) in cases {
+ assert_eq!(
+ kinds(&body(tokens.clone())).unwrap(),
+ expected,
+ "{tokens:?}"
+ );
+ }
+ }
+
+ /// Every opcode's token advance, one row per [`Operation`] variant.
+ ///
+ /// The exhaustive match in `kind_for` catches a *new* opcode. It does not catch an existing one
+ /// gaining an immediate: `kind_for` keeps answering `Bare`, every later instruction decodes at
+ /// the wrong offset, and `GET_GLOBAL` then pops the wrong cells — a confidently wrong read set
+ /// rather than the fail-closed wide one this module exists to produce.
+ ///
+ /// The array is typed `[_; 57]` so the count is load-bearing: a new variant fails to compile
+ /// here rather than being silently skipped. This pins the decoder against itself, not against
+ /// `vm.rs`; a shared arity table both read is the structural fix and a larger change than this.
+ #[test]
+ fn every_opcode_advances_by_exactly_its_immediates() {
+ // (opcode, its immediates, the tokens it consumes after the opcode).
+ let cases: [(Operation, Vec<Value>, usize); 57] = [
+ (Operation::GetGlobal, vec![json!(1)], 1),
+ (Operation::CallGlobal, vec![json!("f"), json!(0)], 2),
+ (Operation::And, vec![json!(2)], 1),
+ (Operation::Or, vec![json!(2)], 1),
+ (Operation::Not, vec![], 0),
+ (Operation::Plus, vec![], 0),
+ (Operation::Minus, vec![], 0),
+ (Operation::Mult, vec![], 0),
+ (Operation::Div, vec![], 0),
+ (Operation::Mod, vec![], 0),
+ (Operation::Eq, vec![], 0),
+ (Operation::NotEq, vec![], 0),
+ (Operation::Gt, vec![], 0),
+ (Operation::GtEq, vec![], 0),
+ (Operation::Lt, vec![], 0),
+ (Operation::LtEq, vec![], 0),
+ (Operation::Like, vec![], 0),
+ (Operation::Ilike, vec![], 0),
+ (Operation::NotLike, vec![], 0),
+ (Operation::NotIlike, vec![], 0),
+ (Operation::In, vec![], 0),
+ (Operation::NotIn, vec![], 0),
+ (Operation::Regex, vec![], 0),
+ (Operation::NotRegex, vec![], 0),
+ (Operation::Iregex, vec![], 0),
+ (Operation::NotIregex, vec![], 0),
+ (Operation::InCohort, vec![], 0),
+ (Operation::NotInCohort, vec![], 0),
+ (Operation::True, vec![], 0),
+ (Operation::False, vec![], 0),
+ (Operation::Null, vec![], 0),
+ (Operation::String, vec![json!("x")], 1),
+ (Operation::Integer, vec![json!(7)], 1),
+ (Operation::Float, vec![json!(1.5)], 1),
+ (Operation::Pop, vec![], 0),
+ (Operation::GetLocal, vec![json!(0)], 1),
+ (Operation::SetLocal, vec![json!(0)], 1),
+ (Operation::Return, vec![], 0),
+ (Operation::Jump, vec![json!(0)], 1),
+ (Operation::JumpIfFalse, vec![json!(0)], 1),
+ // The VM refuses `DECLARE_FN` before it reads an immediate, so there is no arity to
+ // copy and bare is what keeps this decoder aligned with it.
+ (Operation::DeclareFn, vec![], 0),
+ (Operation::Dict, vec![json!(0)], 1),
+ (Operation::Array, vec![json!(0)], 1),
+ (Operation::Tuple, vec![json!(0)], 1),
+ (Operation::GetProperty, vec![], 0),
+ (Operation::SetProperty, vec![], 0),
+ (Operation::JumpIfStackNotNull, vec![json!(0)], 1),
+ (Operation::GetPropertyNullish, vec![], 0),
+ (Operation::Throw, vec![], 0),
+ (Operation::Try, vec![json!(0)], 1),
+ (Operation::PopTry, vec![], 0),
+ // Name, arg count, upvalue count, then an empty body.
+ (
+ Operation::Callable,
+ vec![json!("f"), json!(0), json!(0), json!(0)],
+ 4,
+ ),
+ (Operation::Closure, vec![json!(0)], 1),
+ (Operation::CallLocal, vec![json!(0)], 1),
+ (Operation::GetUpvalue, vec![json!(0)], 1),
+ (Operation::SetUpvalue, vec![json!(0)], 1),
+ (Operation::CloseUpvalue, vec![], 0),
+ ];
+ for (op, immediates, advance) in cases {
+ let mut tokens = vec![json!(op as u8)];
+ tokens.extend(immediates);
+ // A trailing `POP`, which only decodes as an instruction if the opcode before it
+ // consumed exactly `advance` tokens.
+ tokens.push(json!(35));
+ let decoded = decode(&body(tokens))
+ .unwrap_or_else(|error| panic!("{op:?} did not decode: {error}"));
+ assert_eq!(
+ decoded.instrs.len(),
+ 2,
+ "{op:?} left {:?}",
+ decoded
+ .instrs
+ .iter()
+ .map(|instr| instr.kind.clone())
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(
+ decoded.instrs[1].start,
+ TokenIndex(HEADER_LEN + 1 + advance),
+ "{op:?} advanced to the wrong token"
+ );
+ assert_eq!(decoded.instrs[1].kind, InstrKind::Bare(Operation::Pop));
+ }
+ }
+
+ /// A forward jump resolves against the instruction pointer one past its immediate, which is how
+ /// the VM adds the offset. Off by one here would land every conditional on the wrong branch.
+ #[test]
+ fn a_jump_target_is_the_token_the_vm_would_reach() {
+ // Header, then JUMP_IF_FALSE +1 at tokens 2-3, FALSE at 4, TRUE at 5.
+ let decoded = decode(&body(vec![json!(40), json!(1), json!(30), json!(29)])).unwrap();
+ assert_eq!(
+ decoded.instrs[0].kind,
+ InstrKind::Branch {
+ op: Operation::JumpIfFalse,
+ target: Some(TokenIndex(5)),
+ }
+ );
+ assert_eq!(decoded.instrs[0].start, TokenIndex(2));
+ assert_eq!(decoded.body_end, TokenIndex(6));
+ }
+
+ /// Truncation must be an error rather than a short read, in every arity class including the
+ /// variable-length ones. A silent short read would leave the analysis describing a program that
+ /// does not exist.
+ #[test]
+ fn truncated_immediates_are_rejected_in_every_arity_class() {
+ let cases: Vec<(Vec<Value>, Operation)> = vec![
+ (vec![json!(32)], Operation::String),
+ (vec![json!(33)], Operation::Integer),
+ (vec![json!(1)], Operation::GetGlobal),
+ (vec![json!(39)], Operation::Jump),
+ (vec![json!(2), json!("f")], Operation::CallGlobal),
+ (
+ vec![json!(52), json!("f"), json!(0), json!(0)],
+ Operation::Callable,
+ ),
+ // The body runs past the end.
+ (
+ vec![
+ json!(52),
+ json!("f"),
+ json!(0),
+ json!(0),
+ json!(4),
+ json!(29),
+ ],
+ Operation::Callable,
+ ),
+ // The capture pairs run past the end, mid-capture.
+ (
+ vec![json!(53), json!(2), json!(true), json!(0), json!(false)],
+ Operation::Closure,
+ ),
+ ];
+ for (tokens, op) in cases {
+ let error = decode(&body(tokens.clone())).unwrap_err();
+ assert!(
+ matches!(&error, DecodeError::TruncatedImmediates { op: actual, .. } if *actual == op),
+ "{tokens:?} gave {error:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn malformed_immediates_are_rejected_by_kind() {
+ let cases: Vec<(Vec<Value>, Operation)> = vec![
+ (vec![json!(32), json!(7)], Operation::String),
+ (vec![json!(1), json!("two")], Operation::GetGlobal),
+ (vec![json!(1), json!(-1)], Operation::GetGlobal),
+ (vec![json!(39), json!("far")], Operation::Jump),
+ (vec![json!(2), json!(7), json!(1)], Operation::CallGlobal),
+ ];
+ for (tokens, op) in cases {
+ let error = decode(&body(tokens.clone())).unwrap_err();
+ assert!(
+ matches!(&error, DecodeError::MalformedImmediate { op: actual, .. } if *actual == op),
+ "{tokens:?} gave {error:?}"
+ );
+ }
+ }
+
+ /// A count immediate larger than the whole program is refused at the source. Downstream, these
+ /// counts size allocations, so `u64::MAX` is a capacity-overflow panic and a merely huge value
+ /// is an allocation abort — on the orchestrator's own task, from one catalog row.
+ #[test]
+ fn a_count_immediate_larger_than_the_program_is_refused() {
+ for count in [json!(u64::MAX), json!(4_000_000_000u64), json!(1_000)] {
+ let error = decode(&body(vec![json!(1), count.clone()])).unwrap_err();
+ assert!(
+ matches!(
+ &error,
+ DecodeError::MalformedImmediate {
+ op: Operation::GetGlobal,
+ ..
+ }
+ ),
+ "GET_GLOBAL {count} gave {error:?}"
+ );
+ }
+ }
+
+ /// A jump that would land before the start of the array has no landing site, which decode
+ /// records rather than refuses. Refusing it here would fail the whole program over an offset no
+ /// path may even follow; the analysis layer decides that on visit. One past the end is a
+ /// different case again: it is where a jump off the end legitimately lands.
+ #[test]
+ fn a_jump_landing_outside_the_addressable_range_has_no_target() {
+ assert_eq!(
+ kinds(&body(vec![json!(39), json!(-99)])).unwrap(),
+ vec![InstrKind::Branch {
+ op: Operation::Jump,
+ target: None,
+ }]
+ );
+ assert_eq!(
+ kinds(&body(vec![json!(39), json!(0)])).unwrap(),
+ vec![InstrKind::Branch {
+ op: Operation::Jump,
+ target: Some(TokenIndex(4)),
+ }]
+ );
+ }
+
+ #[test]
+ fn a_token_that_is_not_an_opcode_is_rejected_with_its_position() {
+ assert_eq!(
+ decode(&body(vec![json!(11), json!(99)])).unwrap_err(),
+ DecodeError::NotAnOpcode { ip: 3 }
+ );
+ assert_eq!(
+ decode(&body(vec![json!("bare")])).unwrap_err(),
+ DecodeError::NotAnOpcode { ip: 2 }
+ );
+ }
+
+ /// A `CALLABLE` body decodes in place, so its positions and any jump inside it resolve exactly
+ /// as they would when the enclosing program runs.
+ #[test]
+ fn a_callable_body_decodes_at_its_absolute_positions() {
+ let tokens = body(vec![
+ json!(52),
+ json!("f"),
+ json!(0),
+ json!(0),
+ json!(3),
+ json!(32),
+ json!("x"),
+ json!(38),
+ ]);
+ let InstrKind::Callable { body: span } = decode(&tokens).unwrap().instrs[0].kind.clone()
+ else {
+ panic!("the first instruction is not a callable");
+ };
+ let decoded = decode_span(&tokens, span).unwrap();
+ assert_eq!(decoded.instrs[0].start, TokenIndex(7));
+ assert_eq!(
+ decoded
+ .instrs
+ .into_iter()
+ .map(|instr| instr.kind)
+ .collect::<Vec<_>>(),
+ vec![
+ InstrKind::String(Arc::from("x")),
+ InstrKind::Bare(Operation::Return),
+ ]
+ );
+ }
+
+ /// The header rules mirror the VM's: `_H` is mandatory, an unsigned-integer version token is
+ /// consumed, and anything else is an error rather than a first opcode.
+ ///
+ /// The version cases are the ones worth pinning. `Program::from_shared` takes the token through
+ /// `as_u64`, so a negative or fractional version is bytecode the VM will not load; a decoder
+ /// that accepted it would report a read set for a program that never runs.
+ #[test]
+ fn the_header_is_read_exactly_as_the_vm_reads_it() {
+ assert_eq!(decode(&[]).unwrap_err(), DecodeError::MissingHeader);
+ assert_eq!(
+ decode(&[json!(1), json!(32)]).unwrap_err(),
+ DecodeError::MissingHeader
+ );
+ for version in [json!("v1"), json!(-1), json!(1.5), json!(null)] {
+ assert_eq!(
+ decode(&[json!("_H"), version.clone()]).unwrap_err(),
+ DecodeError::MalformedVersion,
+ "version {version} decoded but the VM refuses it"
+ );
+ }
+ // A bare marker is a valid, empty program.
+ assert_eq!(kinds(&[json!("_H")]).unwrap(), Vec::new());
+ assert_eq!(kinds(&[json!("_H"), json!(1)]).unwrap(), Vec::new());
+ // The version slot is consumed even when it holds what looks like an opcode, because the
+ // VM consumes it too.
+ assert_eq!(
+ kinds(&[json!("_H"), json!(35), json!(35)]).unwrap(),
+ vec![InstrKind::Bare(Operation::Pop)]
+ );
+ }
+}
diff --git a/rust/cohort-core/src/hogvm/analysis/event_only.rs b/rust/cohort-core/src/hogvm/analysis/event_only.rs
new file mode 100644
index 000000000000..0107b7e4f013
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/analysis/event_only.rs
@@ -0,0 +1,172 @@
+//! Recognizes the one bytecode shape that is nothing but an event-name equality.
+//!
+//! A scan already filters on event name, so such a condition is decided before any row is read.
+//! The match is positional over the raw tokens with a single hole for the name, rather than a rule
+//! over the decoded instructions: the value of recognizing this shape is that it is exact, and a
+//! looser rule risks claiming a condition needs no evaluation when it does.
+
+use hogvm::Operation;
+use serde_json::Value;
+
+use super::EvaluationClass;
+
+/// `["_H", <version>, STRING, <name>, STRING, "event", GET_GLOBAL, 1, EQ]`, as the compiler emits
+/// `event == '<name>'`, followed by the `RETURN` the catalog loader appends.
+const PREFIX_LEN: usize = 2;
+
+/// The opcodes as they appear on the wire. Derived from [`Operation`] rather than written out:
+/// its discriminants *are* the wire format, so a renumbering that breaks decoding must break this
+/// matcher too. A hand-copied table would instead keep matching the old numbers and silently
+/// classify the wrong programs as event-only.
+const OP_STRING: u64 = Operation::String as u64;
+const OP_GET_GLOBAL: u64 = Operation::GetGlobal as u64;
+const OP_EQ: u64 = Operation::Eq as u64;
+const OP_RETURN: u64 = Operation::Return as u64;
+
+pub(super) fn classify(bytecode: &[Value]) -> EvaluationClass {
+ match match_event_equality(bytecode) {
+ Some(event) => EvaluationClass::EventOnly { event },
+ None => EvaluationClass::General,
+ }
+}
+
+fn match_event_equality(bytecode: &[Value]) -> Option<String> {
+ // Version-0 bytecode carries no version token, so the body would start one slot earlier. The
+ // compiler has emitted a version for as long as these catalogs have existed, so this matcher
+ // requires one and anything else falls through to a general classification.
+ //
+ // `as_u64`, not `is_number`: the VM refuses a fractional or negative version outright, so a
+ // program carrying one never runs. Accepting it here would classify a program the VM rejects as
+ // needing no evaluation, which is the one direction this matcher must not be wrong in.
+ if bytecode.first()?.as_str()? != "_H" || bytecode.get(1)?.as_u64().is_none() {
+ return None;
+ }
+ let body = &bytecode[PREFIX_LEN..];
+ let [push_name, name, push_event, event_key, get_global, chain_len, eq, rest @ ..] = body
+ else {
+ return None;
+ };
+ let opcodes_match = number(push_name) == Some(OP_STRING)
+ && number(push_event) == Some(OP_STRING)
+ && event_key.as_str() == Some("event")
+ && number(get_global) == Some(OP_GET_GLOBAL)
+ && number(chain_len) == Some(1)
+ && number(eq) == Some(OP_EQ);
+ if !opcodes_match {
+ return None;
+ }
+ // The loader appends a `RETURN` to bytecode that may already end in one, so one or more is the
+ // expected tail. Anything else means the program does more than the equality.
+ if rest.is_empty() || !rest.iter().all(|token| number(token) == Some(OP_RETURN)) {
+ return None;
+ }
+ Some(name.as_str()?.to_owned())
+}
+
+fn number(token: &Value) -> Option<u64> {
+ token.as_u64()
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ fn event_equality(name: &str) -> Vec<Value> {
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!(name),
+ json!(32),
+ json!("event"),
+ json!(1),
+ json!(1),
+ json!(11),
+ json!(38),
+ ]
+ }
+
+ #[test]
+ fn the_event_equality_shape_is_recognized_with_its_name() {
+ assert_eq!(
+ classify(&event_equality("purchase")),
+ EvaluationClass::EventOnly {
+ event: "purchase".to_owned()
+ }
+ );
+ }
+
+ /// The catalog loader appends a `RETURN` to bytecode that may already end in one, so the shape
+ /// reaches this matcher with either tail.
+ #[test]
+ fn a_repeated_trailing_return_still_matches() {
+ let mut doubled = event_equality("purchase");
+ doubled.push(json!(38));
+ assert_eq!(
+ classify(&doubled),
+ EvaluationClass::EventOnly {
+ event: "purchase".to_owned()
+ }
+ );
+ }
+
+ /// Every near miss must classify as general. Reading any of these as event-only would skip the
+ /// per-row evaluation the condition actually needs, and admit rows that do not match.
+ #[test]
+ fn near_misses_all_classify_as_general() {
+ let cases: Vec<(&str, Vec<Value>)> = vec![
+ ("missing header", event_equality("purchase")[1..].to_vec()),
+ ("no version token", {
+ let mut tokens = event_equality("purchase");
+ tokens.remove(1);
+ tokens
+ }),
+ ("greater-or-equal instead of equality", {
+ let mut tokens = event_equality("purchase");
+ tokens[8] = json!(14);
+ tokens
+ }),
+ ("a different global", {
+ let mut tokens = event_equality("purchase");
+ tokens[5] = json!("distinct_id");
+ tokens
+ }),
+ ("a two-segment global chain", {
+ let mut tokens = event_equality("purchase");
+ tokens[7] = json!(2);
+ tokens
+ }),
+ ("an extra instruction before the return", {
+ let mut tokens = event_equality("purchase");
+ tokens.insert(9, json!(5));
+ tokens
+ }),
+ ("no return at all", event_equality("purchase")[..9].to_vec()),
+ ("a non-literal event name", {
+ let mut tokens = event_equality("purchase");
+ tokens[3] = json!(7);
+ tokens
+ }),
+ ("empty bytecode", Vec::new()),
+ ("header only", vec![json!("_H"), json!(1)]),
+ // The VM refuses a version it cannot read as a `u64`, so these programs never run.
+ // Classifying one as event-only would say "needs no evaluation" about a program that
+ // would in fact have errored.
+ ("a negative version", {
+ let mut tokens = event_equality("purchase");
+ tokens[1] = json!(-1);
+ tokens
+ }),
+ ("a fractional version", {
+ let mut tokens = event_equality("purchase");
+ tokens[1] = json!(1.5);
+ tokens
+ }),
+ ];
+ for (label, tokens) in cases {
+ assert_eq!(classify(&tokens), EvaluationClass::General, "{label}");
+ }
+ }
+}
diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rs
new file mode 100644
index 000000000000..887a596dc5ba
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs
@@ -0,0 +1,471 @@
+//! Static analysis of a pinned condition's HogVM bytecode: which event globals it reads, and
+//! whether it is nothing more than an event-name equality. Depends on `hogvm::Operation` only.
+//!
+//! Cohort policy stays out of the shared `common/hogvm` crate, the same way [`super::executor`]
+//! layers evaluation on top of the VM's primitives rather than changing them.
+//!
+//! # Fail closed
+//!
+//! Every unmodeled input becomes [`Projection::FullColumns`], which means "read everything". A
+//! caller acting on the result is then slower than it could be, never wrong. That is why
+//! [`analyze_condition`] is total: it returns no error and never panics, because the alternative
+//! (treating an analysis failure as "reads nothing") would silently drop rows from a scan.
+//!
+//! # Why the read set can be trusted
+//!
+//! `GET_GLOBAL` is the VM's only path into the globals dict, and it takes its path from literal
+//! strings the compiler pushed. Every other opcode consumes values already on the stack. So a
+//! program whose `GET_GLOBAL`s all resolve to literal paths cannot reach a global this analysis did
+//! not record, however it combines those values afterwards.
+
+mod decode;
+mod event_only;
+mod projection;
+
+use std::collections::BTreeSet;
+
+use hogvm::Operation;
+use serde_json::Value;
+
+pub use decode::DecodeError;
+pub use projection::AnalysisBudget;
+
+/// What a static pass could establish about one condition's bytecode.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConditionAnalysis {
+ pub evaluation: EvaluationClass,
+ pub projection: Projection,
+}
+
+/// How much of the VM a condition actually needs.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum EvaluationClass {
+ /// The whole program is `event == <name>`. Such a condition is decided by the event name a
+ /// scan already filters on, so it needs no per-row evaluation at all.
+ EventOnly { event: String },
+ /// Anything else.
+ General,
+}
+
+/// The globals a condition reads, when they can be named.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Projection {
+ /// Exactly these paths, and nothing else. Empty means the program reads no globals.
+ ///
+ /// A path names a subtree, not a leaf: `person.properties` claims everything under it, because
+ /// the program may hand that object to a function that indexes it at runtime. A caller
+ /// building a projection has to supply the whole subtree each path names. The analysis never
+ /// returns a bare object root here — [`FullColumnsReason::BarePropertiesRoot`] and
+ /// [`FullColumnsReason::BarePersonRoot`] carry those — so a `Reads` path is always at least one
+ /// key deep under `properties`, `person`, or `pdi`.
+ Reads(BTreeSet<ReadPath>),
+ /// The read set could not be narrowed, so a caller must supply every column.
+ FullColumns(FullColumnsReason),
+}
+
+/// Why a condition fell back to every column. The two bare-root cases are ordinary programs whose
+/// reads genuinely cannot be narrowed; [`FullColumnsReason::Unanalyzable`] is the fail-closed arm.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum FullColumnsReason {
+ /// The program passes the whole `properties` dict somewhere, for example to a function.
+ BarePropertiesRoot,
+ /// The program passes the whole `person` object somewhere.
+ BarePersonRoot,
+ Unanalyzable(UnanalyzableReason),
+}
+
+impl FullColumnsReason {
+ /// A closed, bounded label. Safe as a metric dimension: it never carries program text.
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::BarePropertiesRoot => "bare_properties_root",
+ Self::BarePersonRoot => "bare_person_root",
+ Self::Unanalyzable(reason) => reason.as_str(),
+ }
+ }
+
+ /// Which opcode stopped the analysis, when one did. See [`UnanalyzableReason::op`].
+ pub fn op(&self) -> Option<Operation> {
+ match self {
+ Self::Unanalyzable(reason) => reason.op(),
+ Self::BarePropertiesRoot | Self::BarePersonRoot => None,
+ }
+ }
+}
+
+/// Why a program escaped the abstract model. Each variant is a closed metric label, so this
+/// vocabulary is what a census reports on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UnanalyzableReason {
+ Decode(DecodeError),
+ /// An opcode whose effect the model does not reproduce: a frame, a heap write, or an exception
+ /// handler.
+ UnsupportedOp(Operation),
+ /// A global root outside [`GlobalRoot`], so the program reads something this build cannot name.
+ UnknownGlobalRoot(String),
+ /// A `GET_GLOBAL` path segment that is not a compile-time literal.
+ DynamicGlobalPath,
+ StackUnderflow,
+ /// `GET_GLOBAL 0`, which the VM itself rejects.
+ ZeroLengthGlobalChain,
+ /// Two paths reached one instruction holding stacks of different depths, so the model has lost
+ /// the layout every later `GET_GLOBAL` depends on.
+ StackDepthMismatch,
+ /// A jump landing inside an instruction rather than on one, which the VM would read as an
+ /// opcode where an immediate is.
+ BadJumpTarget,
+ /// The worklist ran past its step ceiling, so the fixpoint argument does not hold for this
+ /// program. Never expected on its own; it exists so an unforeseen shape is a wide answer, not a
+ /// hang. Also how a condition reports a shared [`AnalysisBudget`] its siblings already spent.
+ IterationBudget,
+ /// The pass would have had to hold or copy more abstract stack state than its ceiling allows.
+ /// Bounds the memory and the copying a condition can cost, whatever its branching shape, and
+ /// reports a shared [`AnalysisBudget`] spent down to its cell half.
+ StateBudget,
+ /// A local slot outside the current frame, which the VM's own bounds check refuses.
+ LocalSlotOutOfRange,
+ /// A `RETURN` that left values on the stack, meaning a stack effect in the transfer table is
+ /// wrong.
+ UnbalancedReturn,
+}
+
+impl UnanalyzableReason {
+ /// A closed, bounded label. The payloads (an opcode, a root name, a decode position) stay out
+ /// of it, so it is safe as a metric dimension however hostile the bytecode is. Use
+ /// [`Self::op`] for the one payload that is itself bounded.
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::Decode(_) => "decode",
+ Self::UnsupportedOp(_) => "unsupported_op",
+ Self::UnknownGlobalRoot(_) => "unknown_global_root",
+ Self::DynamicGlobalPath => "dynamic_global_path",
+ Self::StackUnderflow => "stack_underflow",
+ Self::ZeroLengthGlobalChain => "zero_length_global_chain",
+ Self::StackDepthMismatch => "stack_depth_mismatch",
+ Self::BadJumpTarget => "bad_jump_target",
+ Self::IterationBudget => "iteration_budget",
+ Self::StateBudget => "state_budget",
+ Self::LocalSlotOutOfRange => "local_slot_out_of_range",
+ Self::UnbalancedReturn => "unbalanced_return",
+ }
+ }
+
+ /// Which opcode stopped the analysis, when one did.
+ ///
+ /// [`Operation`] is a closed 57-variant enum, so this is as bounded as [`Self::as_str`] and
+ /// safe as a second metric dimension — unlike [`Self::UnknownGlobalRoot`]'s payload, which is
+ /// customer-shaped. It is worth carrying because "unsupported_op" alone cannot tell one
+ /// fixable compiler template apart from a genuinely unreadable program.
+ ///
+ /// A decode failure names its opcode too, and that is the case the label earns the most: a
+ /// decoder whose immediate table drifts from `vm.rs` fails on the opcode that drifted.
+ /// Exhaustive rather than defaulted, so a new variant has to decide.
+ pub fn op(&self) -> Option<Operation> {
+ match self {
+ Self::Decode(error) => error.op(),
+ Self::UnsupportedOp(op) => Some(*op),
+ Self::UnknownGlobalRoot(_)
+ | Self::DynamicGlobalPath
+ | Self::StackUnderflow
+ | Self::ZeroLengthGlobalChain
+ | Self::StackDepthMismatch
+ | Self::BadJumpTarget
+ | Self::IterationBudget
+ | Self::StateBudget
+ | Self::LocalSlotOutOfRange
+ | Self::UnbalancedReturn => None,
+ }
+ }
+}
+
+/// One global the program reads, as a root plus the keys taken under it. `Ord` so a
+/// [`BTreeSet`] of these has a stable order, which keeps a census reproducible.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub struct ReadPath {
+ pub root: GlobalRoot,
+ pub segments: Vec<String>,
+}
+
+impl ReadPath {
+ pub fn new(root: GlobalRoot, segments: Vec<String>) -> Self {
+ Self { root, segments }
+ }
+
+ /// The dotted rendering, for logs and census output.
+ pub fn render(&self) -> String {
+ let mut rendered = self.root.as_str().to_owned();
+ for segment in &self.segments {
+ rendered.push('.');
+ rendered.push_str(segment);
+ }
+ rendered
+ }
+}
+
+/// A group ordinal, which the behavioral globals define for 0 through 4.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct GroupIndex(u8);
+
+impl GroupIndex {
+ pub const COUNT: u8 = 5;
+
+ pub fn parse(index: u8) -> Option<Self> {
+ (index < Self::COUNT).then_some(Self(index))
+ }
+
+ pub const fn get(self) -> u8 {
+ self.0
+ }
+}
+
+/// The roots of the behavioral globals dict, which is the whole surface a condition can read.
+///
+/// A root outside this list fails closed through [`UnanalyzableReason::UnknownGlobalRoot`]: if the
+/// globals gain a key and this enum does not, the analysis reports it rather than claiming a
+/// narrower read set than the program has.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub enum GlobalRoot {
+ Event,
+ Uuid,
+ ElementsChain,
+ ElementsChainHref,
+ ElementsChainTexts,
+ ElementsChainIds,
+ ElementsChainElements,
+ Timestamp,
+ Properties,
+ Person,
+ Pdi,
+ DistinctId,
+ DollarGroup(GroupIndex),
+ Group(GroupIndex),
+ Variables,
+}
+
+impl GlobalRoot {
+ /// Resolve a literal root name. `None` means the name is not a behavioral global.
+ pub fn parse(name: &str) -> Option<Self> {
+ match name {
+ "event" => Some(Self::Event),
+ "uuid" => Some(Self::Uuid),
+ "elements_chain" => Some(Self::ElementsChain),
+ "elements_chain_href" => Some(Self::ElementsChainHref),
+ "elements_chain_texts" => Some(Self::ElementsChainTexts),
+ "elements_chain_ids" => Some(Self::ElementsChainIds),
+ "elements_chain_elements" => Some(Self::ElementsChainElements),
+ "timestamp" => Some(Self::Timestamp),
+ "properties" => Some(Self::Properties),
+ "person" => Some(Self::Person),
+ "pdi" => Some(Self::Pdi),
+ "distinct_id" => Some(Self::DistinctId),
+ "variables" => Some(Self::Variables),
+ _ => name
+ .strip_prefix("$group_")
+ .and_then(group_index)
+ .map(Self::DollarGroup)
+ .or_else(|| {
+ name.strip_prefix("group_")
+ .and_then(group_index)
+ .map(Self::Group)
+ }),
+ }
+ }
+
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::Event => "event",
+ Self::Uuid => "uuid",
+ Self::ElementsChain => "elements_chain",
+ Self::ElementsChainHref => "elements_chain_href",
+ Self::ElementsChainTexts => "elements_chain_texts",
+ Self::ElementsChainIds => "elements_chain_ids",
+ Self::ElementsChainElements => "elements_chain_elements",
+ Self::Timestamp => "timestamp",
+ Self::Properties => "properties",
+ Self::Person => "person",
+ Self::Pdi => "pdi",
+ Self::DistinctId => "distinct_id",
+ Self::DollarGroup(index) => DOLLAR_GROUP_NAMES[index.get() as usize],
+ Self::Group(index) => GROUP_NAMES[index.get() as usize],
+ Self::Variables => "variables",
+ }
+ }
+}
+
+const DOLLAR_GROUP_NAMES: [&str; GroupIndex::COUNT as usize] =
+ ["$group_0", "$group_1", "$group_2", "$group_3", "$group_4"];
+const GROUP_NAMES: [&str; GroupIndex::COUNT as usize] =
+ ["group_0", "group_1", "group_2", "group_3", "group_4"];
+
+/// A single-digit group ordinal, rejecting `group_00` and `group_10` alike.
+fn group_index(suffix: &str) -> Option<GroupIndex> {
+ let [digit] = suffix.as_bytes() else {
+ return None;
+ };
+ GroupIndex::parse(digit.checked_sub(b'0')?)
+}
+
+/// Analyze one condition's loaded bytecode, under a budget of its own.
+///
+/// Total: it returns no error and never panics. Anything the model does not cover becomes
+/// [`Projection::FullColumns`] carrying the reason, because a wrong narrow answer would drop rows
+/// from a scan while a wide one only costs time.
+pub fn analyze_condition(bytecode: &[Value]) -> ConditionAnalysis {
+ analyze_condition_within(bytecode, &mut AnalysisBudget::for_one_condition())
+}
+
+/// Analyze one condition against a budget its siblings share.
+///
+/// A caller with many conditions wants the batch bounded, not each member of it: the per-condition
+/// ceilings leave `conditions × ceiling`, which is unbounded wherever nothing caps the conditions.
+/// Spending one budget in a fixed order keeps that bounded and keeps the analysis a pure function
+/// of its input, so the same batch always classifies the same way.
+pub fn analyze_condition_within(
+ bytecode: &[Value],
+ budget: &mut AnalysisBudget,
+) -> ConditionAnalysis {
+ ConditionAnalysis {
+ evaluation: event_only::classify(bytecode),
+ projection: projection::project(bytecode, budget),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ /// The assumption the read set rests on, checked against the VM's own standard library.
+ ///
+ /// A `CALL_GLOBAL` to a hog-implemented standard-library function is not a native call: the VM
+ /// pushes a frame and runs that function's body against the *same* globals dict. The abstract
+ /// interpreter does not follow the callee, so if any of those bodies read a global, a condition
+ /// calling it would read a global this analysis never recorded, and a projection built from the
+ /// claimed set would evaluate it against a truncated event.
+ ///
+ /// Today no standard-library body contains a `GET_GLOBAL`; they work purely on their arguments.
+ /// This fails if one ever does, which is the moment `CALL_GLOBAL` would stop being safe to treat
+ /// as a plain stack reduction.
+ ///
+ /// A body may itself define a lambda, whose tokens `decode` steps over rather than into —
+ /// `sortableSemver` already does. Those tokens are still code the VM runs against the same
+ /// globals dict, so the scan follows every nested `CALLABLE` body too. Without that, the check
+ /// would pass on exactly the shape it exists to catch.
+ #[test]
+ fn no_standard_library_function_body_reads_a_global() {
+ let module = hogvm::hog_stl();
+ let functions = module.functions();
+ assert!(
+ !functions.is_empty(),
+ "the standard library is empty, so this check would pass vacuously"
+ );
+ let mut nested_bodies_seen = 0;
+ for (name, function) in functions {
+ // The bodies are raw instruction lists, so give them the header the decoder expects.
+ let mut body = vec![json!("_H"), json!(1)];
+ let mut index = 0;
+ while let Some(token) = function.get(index) {
+ body.push(token.clone());
+ index += 1;
+ }
+ let decoded = decode::decode(&body).unwrap_or_else(|error| {
+ panic!("standard library function {name} did not decode: {error}")
+ });
+ let mut pending = vec![decoded];
+ while let Some(decoded) = pending.pop() {
+ for instr in &decoded.instrs {
+ assert!(
+ !matches!(
+ instr.kind,
+ decode::InstrKind::Counted(Operation::GetGlobal, _)
+ ),
+ "standard library function {name} reads a global, so a condition calling \
+ it would read globals this analysis does not record"
+ );
+ if let decode::InstrKind::Callable { body: span } = instr.kind {
+ nested_bodies_seen += 1;
+ pending.push(decode::decode_span(&body, span).unwrap_or_else(|error| {
+ panic!("a lambda body in {name} did not decode: {error}")
+ }));
+ }
+ }
+ }
+ }
+ assert!(
+ nested_bodies_seen > 0,
+ "no standard library function defines a lambda, so the recursion is untested"
+ );
+ }
+
+ #[test]
+ fn every_behavioral_global_root_round_trips_through_its_name() {
+ let roots = [
+ GlobalRoot::Event,
+ GlobalRoot::Uuid,
+ GlobalRoot::ElementsChain,
+ GlobalRoot::ElementsChainHref,
+ GlobalRoot::ElementsChainTexts,
+ GlobalRoot::ElementsChainIds,
+ GlobalRoot::ElementsChainElements,
+ GlobalRoot::Timestamp,
+ GlobalRoot::Properties,
+ GlobalRoot::Person,
+ GlobalRoot::Pdi,
+ GlobalRoot::DistinctId,
+ GlobalRoot::Variables,
+ ];
+ for root in roots {
+ assert_eq!(GlobalRoot::parse(root.as_str()), Some(root.clone()));
+ }
+ for index in 0..GroupIndex::COUNT {
+ let index = GroupIndex::parse(index).unwrap();
+ for root in [GlobalRoot::DollarGroup(index), GlobalRoot::Group(index)] {
+ assert_eq!(GlobalRoot::parse(root.as_str()), Some(root.clone()));
+ }
+ }
+ }
+
+ /// A name close to a real root must not resolve to one. Accepting `group_9` would let the
+ /// analysis claim a read of a global the event does not carry.
+ #[test]
+ fn near_miss_root_names_do_not_resolve() {
+ for name in [
+ "group_5",
+ "group_9",
+ "group_00",
+ "group_10",
+ "group_",
+ "$group_5",
+ "$group_",
+ "Event",
+ "properties2",
+ "",
+ "person.properties",
+ ] {
+ assert_eq!(GlobalRoot::parse(name), None, "{name} resolved to a root");
+ }
+ }
+
+ #[test]
+ fn read_paths_render_dotted_and_sort_by_root_then_segments() {
+ let path = ReadPath::new(
+ GlobalRoot::Person,
+ vec!["properties".to_owned(), "email".to_owned()],
+ );
+ assert_eq!(path.render(), "person.properties.email");
+ assert_eq!(
+ ReadPath::new(GlobalRoot::Event, Vec::new()).render(),
+ "event"
+ );
+
+ let mut set = BTreeSet::new();
+ set.insert(ReadPath::new(GlobalRoot::Properties, vec!["b".to_owned()]));
+ set.insert(ReadPath::new(GlobalRoot::Event, Vec::new()));
+ set.insert(ReadPath::new(GlobalRoot::Properties, vec!["a".to_owned()]));
+ assert_eq!(
+ set.iter().map(ReadPath::render).collect::<Vec<_>>(),
+ ["event", "properties.a", "properties.b"]
+ );
+ }
+}
diff --git a/rust/cohort-core/src/hogvm/analysis/projection.rs b/rust/cohort-core/src/hogvm/analysis/projection.rs
new file mode 100644
index 000000000000..bcf3c2e20eb1
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/analysis/projection.rs
@@ -0,0 +1,1229 @@
+//! An abstract interpreter over the decoded control-flow graph, producing the set of globals a
+//! condition reads.
+//!
+//! The abstract domain has two values: a compile-time literal string, and everything else. That is
+//! all `GET_GLOBAL` needs, because it builds its path from literal strings the compiler pushed and
+//! nothing else can reach the globals dict.
+//!
+//! Branches are followed rather than refused. A worklist carries an abstract stack along each path;
+//! where paths meet, the stacks are joined cell by cell, and the pass repeats until nothing
+//! changes. That matters because the cohort compiler lowers the ordinary operators through jumps:
+//! `null_safe_comparisons` rewrites every `>`/`>=`/`<`/`<=` into an `if`, regex goes through
+//! `ifNull`, and `between` compiles to a local-slot IIFE. Refusing branches would report almost
+//! every date and regex condition as unreadable.
+//!
+//! Only instructions more than one edge can reach hold a stored stack, and a straight-line run is
+//! walked in place with one stack rather than through the worklist. Both matter for cost, not
+//! elegance: a `properties.x IN (...)` leaf pushes every list element before `IN` pops them, and
+//! catalogs hold lists of several thousand. Storing and copying a stack per instruction over that
+//! is quadratic in the program's own length, which on the largest real list size meant seconds of
+//! blocking and over a gigabyte, for a program the VM evaluates in kilobytes.
+//!
+//! That gating answers the shape it was built for and no other. A program that is *all* merge
+//! points — a deep stack of literals, then a chain of rejoining diamonds — stores and copies a
+//! stack at every one of them, and a transfer-step ceiling does not bound that, because one step
+//! can copy a whole stack. So the two ceilings in [`AnalysisBudget`] are both needed: steps for the
+//! programs that spend without copying, copied cells for the programs that copy without spending.
+//!
+//! The pass stays fail-closed everywhere it is not sure. Two paths that meet at different stack
+//! depths, a jump into the middle of an instruction, a local slot outside the frame, or a `RETURN`
+//! that leaves the stack unbalanced all stop the analysis and widen the condition to every column.
+//! Reads accumulate globally rather than per instruction, so a join can never retract one.
+
+use std::collections::{BTreeSet, VecDeque};
+use std::sync::Arc;
+
+use hogvm::Operation;
+use serde_json::Value;
+
+use super::decode::{decode, Decoded, InstrIndex, InstrKind, TokenIndex};
+use super::{FullColumnsReason, GlobalRoot, Projection, ReadPath, UnanalyzableReason};
+
+/// `elements_chain` falls back to this property when the event's own column is empty, so a caller
+/// that projects an `elements_chain` read must carry it too.
+const ELEMENTS_CHAIN_PROPERTY: &str = "$elements_chain";
+
+/// A ceiling on transfer steps one program may take, so a program the lattice argument does not
+/// cover cannot hang the caller. The fixpoint is reached far sooner: a merge point's stack can only
+/// move upward, one cell at a time, so the work is quadratic in the program length at worst and
+/// this only fires if that reasoning is wrong.
+const MAX_WORKLIST_STEPS: usize = 1_000_000;
+
+/// A ceiling on the abstract stack cells one program may copy in total.
+///
+/// The step ceiling does not bound the work on its own: one step can copy a whole stack at a merge
+/// point, so the two multiply. A deep stack followed by a chain of rejoining diamonds is all merge
+/// points, so merge-point gating does not apply to it, and the pair of ceilings alone admits about
+/// `1e12` cell copies. Charging what is actually copied is what makes the bounded cost the cost
+/// incurred.
+const MAX_COPIED_CELLS: usize = 16_000_000;
+
+/// A ceiling on the abstract stack cells the pass holds at once, across stored merge-point states
+/// and the worklist together. A memory ceiling rather than a work one, so it is per program however
+/// the caller shares [`AnalysisBudget`].
+///
+/// The pass would otherwise be quadratic in a shape production already writes: a `properties.x IN
+/// (...)` leaf pushes every list element before `IN` pops them, and catalogs hold lists of several
+/// thousand. Storing one stack per instruction across such a program is cells proportional to the
+/// square of its length. Merge-point gating removes that for straight-line code; this bounds what
+/// is left, so a shape nobody predicted costs a wide answer rather than the process.
+const MAX_RETAINED_CELLS: usize = 1_000_000;
+
+/// A ceiling on the work an analysis may do, in transfer steps and copied abstract stack cells.
+///
+/// Both units are load-bearing. A step ceiling alone lets one step copy a whole stack, so the two
+/// multiply; a cell ceiling alone says nothing about a straight-line run, which is walked in place
+/// and copies nothing.
+///
+/// A budget may be shared by a batch of conditions, which is how a caller bounds the batch rather
+/// than each member of it: per-condition ceilings alone leave `conditions × ceiling`, and nothing
+/// caps the conditions on a run. Sharing keeps the analysis a pure function of its input — a batch
+/// is analyzed in a fixed order, so it always spends the budget the same way, which a wall-clock
+/// deadline would not. Past the budget every remaining condition reports it and fails closed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AnalysisBudget {
+ /// Transfer steps left to take.
+ pub steps: usize,
+ /// Abstract stack cells left to copy.
+ pub cells: usize,
+}
+
+impl AnalysisBudget {
+ /// What one condition may cost on its own.
+ pub const fn for_one_condition() -> Self {
+ Self {
+ steps: MAX_WORKLIST_STEPS,
+ cells: MAX_COPIED_CELLS,
+ }
+ }
+
+ /// What `worst_case_conditions` conditions cost together, each saturating its own ceiling. The
+ /// unit is a worst case rather than a condition, so a batch of any size fits a budget the
+ /// caller can reason about in wall-clock terms.
+ pub const fn for_conditions(worst_case_conditions: usize) -> Self {
+ Self {
+ steps: MAX_WORKLIST_STEPS.saturating_mul(worst_case_conditions),
+ cells: MAX_COPIED_CELLS.saturating_mul(worst_case_conditions),
+ }
+ }
+
+ fn spend(&mut self, steps: usize, cells: usize) {
+ self.steps = self.steps.saturating_sub(steps);
+ self.cells = self.cells.saturating_sub(cells);
+ }
+}
+
+/// Which instructions more than one edge can reach.
+///
+/// The successor sets are the transfer function's, over-approximated: a conditional jump is counted
+/// as reaching both of its edges even where the interpreter later finds only one live, and a refused
+/// opcode is counted as falling through. Over-approximating only turns more instructions into merge
+/// points, which costs memory and never correctness — while under-approximating would drop a join
+/// and let the pass read a stack no path actually produces.
+fn merge_points(decoded: &Decoded, starts: &[TokenIndex]) -> Vec<bool> {
+ let mut in_degree = vec![0_u32; decoded.instrs.len()];
+ if in_degree.is_empty() {
+ return Vec::new();
+ }
+ // The program is entered at its first instruction, which is an edge like any other: a backward
+ // jump onto it must make it a merge point rather than overwrite the entry state.
+ in_degree[0] = 1;
+ for (index, instr) in decoded.instrs.iter().enumerate() {
+ let falls_through = !matches!(
+ instr.kind,
+ InstrKind::Bare(Operation::Return)
+ | InstrKind::Branch {
+ op: Operation::Jump,
+ ..
+ }
+ );
+ if falls_through && index + 1 < in_degree.len() {
+ in_degree[index + 1] = in_degree[index + 1].saturating_add(1);
+ }
+ if let InstrKind::Branch {
+ target: Some(target),
+ ..
+ } = instr.kind
+ {
+ if let Ok(landed) = starts.binary_search(&target) {
+ in_degree[landed] = in_degree[landed].saturating_add(1);
+ }
+ }
+ }
+ in_degree.into_iter().map(|degree| degree >= 2).collect()
+}
+
+/// One cell of the abstract stack.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum AbstractValue {
+ /// A string literal the compiler pushed, which a `GET_GLOBAL` path may be built from.
+ LiteralString(Arc<str>),
+ /// A value the model cannot name.
+ Opaque,
+}
+
+impl AbstractValue {
+ /// The join of two cells. Two identical literals stay a literal; anything else is the top of
+ /// the two-value lattice, which is what makes the fixpoint terminate.
+ fn join(&self, other: &Self) -> Self {
+ match (self, other) {
+ (Self::LiteralString(left), Self::LiteralString(right)) if left == right => {
+ Self::LiteralString(Arc::clone(left))
+ }
+ _ => Self::Opaque,
+ }
+ }
+}
+
+type AbstractStack = Vec<AbstractValue>;
+
+pub(super) fn project(bytecode: &[Value], budget: &mut AnalysisBudget) -> Projection {
+ // A spent budget stops before the decode too. Decoding is work proportional to the whole
+ // program, so a batch that ran out on its first condition would otherwise still pay it for
+ // every remaining one.
+ if budget.steps == 0 {
+ return full_columns(UnanalyzableReason::IterationBudget);
+ }
+ let decoded = match decode(bytecode) {
+ Ok(decoded) => decoded,
+ Err(error) => return full_columns(UnanalyzableReason::Decode(error)),
+ };
+ let mut interpreter = Interpreter::new(&decoded, *budget);
+ let outcome = interpreter.run();
+ // Charged however the pass ended: a condition that spent the budget and then failed closed has
+ // still spent it.
+ budget.spend(interpreter.steps, interpreter.cells_copied);
+ match outcome {
+ Ok(reads) => Projection::Reads(reads),
+ Err(Stop::Unanalyzable(reason)) => full_columns(reason),
+ Err(Stop::BareRoot(reason)) => Projection::FullColumns(reason),
+ }
+}
+
+fn full_columns(reason: UnanalyzableReason) -> Projection {
+ Projection::FullColumns(FullColumnsReason::Unanalyzable(reason))
+}
+
+/// Why the interpreter stopped early. A bare root is an ordinary program the analysis understood
+/// and cannot narrow; everything else is the fail-closed arm.
+enum Stop {
+ Unanalyzable(UnanalyzableReason),
+ BareRoot(FullColumnsReason),
+}
+
+/// What an instruction does to control flow, after its own stack effect has been applied. Both
+/// conditional jumps produce [`Control::Fork`]: they differ in whether they pop, and that
+/// difference is already spent by the time the successors are computed, so the two edges out of
+/// either one carry the same stack.
+enum Control {
+ /// The program ends on this path.
+ Terminate,
+ /// Continue with the next instruction.
+ Fall,
+ /// Continue at one specific token. `None` is a jump the decoder could not resolve, which
+ /// fails closed here rather than at decode, so a dead one costs nothing.
+ Jump(Option<TokenIndex>),
+ /// Continue at the next instruction and at one specific token.
+ Fork(Option<TokenIndex>),
+}
+
+struct Interpreter<'a> {
+ decoded: &'a Decoded,
+ /// The token each instruction starts at, so a jump target resolves to an instruction. Linear
+ /// rather than a map: programs are short, and this keeps the lookup allocation-free.
+ starts: Vec<TokenIndex>,
+ /// Which instructions more than one edge can reach. Only those need a stored stack to join
+ /// into; the rest have a single predecessor, so their incoming stack is already the joined one
+ /// and is handed straight to them on the worklist.
+ merge_points: Vec<bool>,
+ /// The joined stack every path into a merge point agrees on. Always `None` for the rest, so a
+ /// straight-line program stores nothing at all.
+ entry: Vec<Option<AbstractStack>>,
+ /// Stack cells alive in `entry` and on the worklist together. Bounding this is what keeps the
+ /// pass's memory a function of the program's branching rather than of its length.
+ retained: usize,
+ /// Transfer steps taken and stack cells copied so far. Read back by [`project`] and charged
+ /// against the caller's budget, so a batch sharing one budget pays for what each member spent.
+ steps: usize,
+ cells_copied: usize,
+ /// This program's ceilings: its own, capped by what the caller's budget has left.
+ step_ceiling: usize,
+ cell_ceiling: usize,
+ /// Accumulated across every visit and never retracted. Held outside the per-instruction state
+ /// on purpose: a join that narrowed a read set could make the analysis claim fewer globals
+ /// than the program touches, which is the one failure this module must not have.
+ reads: BTreeSet<ReadPath>,
+ worklist: VecDeque<(InstrIndex, AbstractStack)>,
+}
+
+impl<'a> Interpreter<'a> {
+ fn new(decoded: &'a Decoded, budget: AnalysisBudget) -> Self {
+ let starts: Vec<TokenIndex> = decoded.instrs.iter().map(|instr| instr.start).collect();
+ let count = decoded.instrs.len();
+ // Every instruction is re-processed once per widening of a merge point upstream of it, and
+ // a merge point widens at most once per stack cell. The quadratic term covers that; the
+ // factor is headroom, so a legitimate program never reports the budget instead of an answer.
+ let step_ceiling = count
+ .checked_mul(count + 1)
+ .and_then(|product| product.checked_mul(4))
+ .unwrap_or(MAX_WORKLIST_STEPS)
+ .min(MAX_WORKLIST_STEPS)
+ .min(budget.steps);
+ Self {
+ merge_points: merge_points(decoded, &starts),
+ starts,
+ decoded,
+ entry: vec![None; count],
+ retained: 0,
+ steps: 0,
+ cells_copied: 0,
+ step_ceiling,
+ cell_ceiling: MAX_COPIED_CELLS.min(budget.cells),
+ reads: BTreeSet::new(),
+ worklist: VecDeque::new(),
+ }
+ }
+
+ fn run(&mut self) -> Result<BTreeSet<ReadPath>, Stop> {
+ if self.decoded.instrs.is_empty() {
+ return Ok(BTreeSet::new());
+ }
+ self.enqueue(InstrIndex(0), AbstractStack::new());
+
+ while let Some((InstrIndex(entry_index), stack)) = self.worklist.pop_front() {
+ self.retained -= stack.len();
+ let mut index = entry_index;
+ let mut stack = stack;
+ // Walk the straight-line run out of this instruction in place. Handing each step back
+ // through the worklist would copy the whole stack per instruction, which is a copy per
+ // element of a large `IN` list — quadratic in the program's own length.
+ loop {
+ self.steps += 1;
+ if self.steps > self.step_ceiling {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::IterationBudget));
+ }
+ if self.retained + stack.len() > MAX_RETAINED_CELLS
+ || self.cells_copied > self.cell_ceiling
+ {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::StateBudget));
+ }
+ let next = match self.transfer(index, &mut stack)? {
+ Control::Terminate => break,
+ Control::Fall => self.next_index(index),
+ Control::Jump(target) => self.target_index(target)?,
+ Control::Fork(target) => {
+ // Two live successors, so neither can take the stack by value.
+ self.propagate_next(index, &stack)?;
+ self.propagate_token(target, &stack)?;
+ break;
+ }
+ };
+ let Some(next) = next else {
+ break;
+ };
+ if self.merge_points[next] {
+ self.propagate(InstrIndex(next), &stack)?;
+ break;
+ }
+ index = next;
+ }
+ }
+ Ok(std::mem::take(&mut self.reads))
+ }
+
+ fn enqueue(&mut self, index: InstrIndex, stack: AbstractStack) {
+ // Every stack this pass copies is copied on the way here — the worklist entry itself, and
+ // the merge-point store that precedes it. Charging by cells rather than by step is what
+ // makes the ceiling bound the work: one step can copy a whole stack.
+ self.cells_copied = self.cells_copied.saturating_add(stack.len());
+ self.retained += stack.len();
+ self.worklist.push_back((index, stack));
+ }
+
+ /// The instruction after `index`, or `None` at the end of the program. Running off the end is
+ /// the program stopping, exactly as the VM's step loop stops when its instruction pointer
+ /// leaves the body.
+ fn next_index(&self, index: usize) -> Option<usize> {
+ (index + 1 < self.decoded.instrs.len()).then_some(index + 1)
+ }
+
+ /// The instruction a jump lands on, or `None` when it lands one past the last token — a jump
+ /// off the end, which terminates.
+ fn target_index(&self, target: Option<TokenIndex>) -> Result<Option<usize>, Stop> {
+ let Some(target) = target else {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::BadJumpTarget));
+ };
+ if target == self.decoded.body_end {
+ return Ok(None);
+ }
+ self.starts
+ .binary_search(&target)
+ .map(Some)
+ .map_err(|_| Stop::Unanalyzable(UnanalyzableReason::BadJumpTarget))
+ }
+
+ fn propagate_next(&mut self, index: usize, stack: &AbstractStack) -> Result<(), Stop> {
+ if let Some(next) = self.next_index(index) {
+ self.propagate(InstrIndex(next), stack)?;
+ }
+ Ok(())
+ }
+
+ /// Continue at a jump target. A target that is neither an instruction boundary nor the end of
+ /// the program fails closed: the VM would read an immediate as an opcode there.
+ fn propagate_token(
+ &mut self,
+ target: Option<TokenIndex>,
+ stack: &AbstractStack,
+ ) -> Result<(), Stop> {
+ match self.target_index(target)? {
+ Some(index) => self.propagate(InstrIndex(index), stack),
+ None => Ok(()),
+ }
+ }
+
+ fn propagate(
+ &mut self,
+ InstrIndex(index): InstrIndex,
+ stack: &AbstractStack,
+ ) -> Result<(), Stop> {
+ if self.retained > MAX_RETAINED_CELLS {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::StateBudget));
+ }
+ // A single-predecessor instruction has nothing to join against, so its stack goes straight
+ // onto the worklist and is never stored. That is what keeps a long straight-line program —
+ // the shape a large `IN` list compiles to — from retaining one stack per instruction.
+ if !self.merge_points[index] {
+ self.enqueue(InstrIndex(index), stack.clone());
+ return Ok(());
+ }
+ match &self.entry[index] {
+ None => {
+ self.retained += stack.len();
+ self.entry[index] = Some(stack.clone());
+ self.enqueue(InstrIndex(index), stack.clone());
+ Ok(())
+ }
+ Some(existing) => {
+ // Two paths reaching one instruction with different stack depths means the model
+ // has lost track of the layout, and every later `GET_GLOBAL` would pop the wrong
+ // cells. There is no join that recovers from it, so the program fails closed.
+ if existing.len() != stack.len() {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::StackDepthMismatch));
+ }
+ let joined: AbstractStack = existing
+ .iter()
+ .zip(stack)
+ .map(|(left, right)| left.join(right))
+ .collect();
+ if joined != *existing {
+ self.entry[index] = Some(joined.clone());
+ self.enqueue(InstrIndex(index), joined);
+ }
+ Ok(())
+ }
+ }
+ }
+
+ fn transfer(&mut self, index: usize, stack: &mut AbstractStack) -> Result<Control, Stop> {
+ match &self.decoded.instrs[index].kind {
+ InstrKind::String(literal) => {
+ stack.push(AbstractValue::LiteralString(Arc::clone(literal)));
+ Ok(Control::Fall)
+ }
+ InstrKind::Number(_) => push_opaque(stack),
+ InstrKind::Counted(op, count) => self.counted(*op, *count, stack),
+ // Any callee name is projection-safe. A native consumes stack values and cannot reach
+ // the globals dict, which is what keeps `toDateTime(timestamp) > x` projectable.
+ InstrKind::CallGlobal { argc, .. } => reduce(stack, *argc),
+ InstrKind::Bare(op) => self.bare(*op, stack),
+ InstrKind::Branch { op, target } => branch(*op, *target, stack),
+ // A callable or closure introduces a frame the model has no notion of, and `TRY`
+ // installs a handler that can enter one from anywhere. Refused on visit, so an
+ // occurrence in code no path reaches costs nothing.
+ InstrKind::Callable { .. } => Err(unsupported(Operation::Callable)),
+ InstrKind::Closure => Err(unsupported(Operation::Closure)),
+ InstrKind::Try => Err(unsupported(Operation::Try)),
+ }
+ }
+
+ fn counted(
+ &mut self,
+ op: Operation,
+ count: usize,
+ stack: &mut AbstractStack,
+ ) -> Result<Control, Stop> {
+ match op {
+ Operation::GetGlobal => self.get_global(count, stack),
+ Operation::Dict => reduce(stack, count.saturating_mul(2)),
+ // The compiler emits `AND n` / `OR n` rather than a jump-form short circuit, so these
+ // stay plain reductions.
+ Operation::And | Operation::Or | Operation::Array | Operation::Tuple => {
+ reduce(stack, count)
+ }
+ // The frame base is zero: `CALLABLE`, `CLOSURE`, and `CALL_LOCAL` are all refused, so
+ // no path reaching here has pushed a frame, and a slot offset indexes the stack
+ // directly. That is what makes the `between` IIFE readable.
+ Operation::GetLocal => {
+ let value = stack
+ .get(count)
+ .ok_or(Stop::Unanalyzable(UnanalyzableReason::LocalSlotOutOfRange))?
+ .clone();
+ stack.push(value);
+ Ok(Control::Fall)
+ }
+ Operation::SetLocal => {
+ let value = pop(stack)?;
+ // The VM pops before it indexes, so a slot equal to the post-pop depth is out of
+ // range there too.
+ let slot = stack
+ .get_mut(count)
+ .ok_or(Stop::Unanalyzable(UnanalyzableReason::LocalSlotOutOfRange))?;
+ *slot = value;
+ Ok(Control::Fall)
+ }
+ // Upvalue slots address a closure's captured environment, which only the refused frame
+ // opcodes create.
+ Operation::GetUpvalue | Operation::SetUpvalue | Operation::CallLocal => {
+ Err(unsupported(op))
+ }
+ // `decode` builds `Counted` only from the opcodes above.
+ other => Err(unsupported(other)),
+ }
+ }
+
+ fn bare(&mut self, op: Operation, stack: &mut AbstractStack) -> Result<Control, Stop> {
+ match op {
+ Operation::True | Operation::False | Operation::Null => push_opaque(stack),
+ Operation::Not => reduce(stack, 1),
+ Operation::Plus
+ | Operation::Minus
+ | Operation::Mult
+ | Operation::Div
+ | Operation::Mod
+ | Operation::Eq
+ | Operation::NotEq
+ | Operation::Gt
+ | Operation::GtEq
+ | Operation::Lt
+ | Operation::LtEq
+ | Operation::Like
+ | Operation::Ilike
+ | Operation::NotLike
+ | Operation::NotIlike
+ | Operation::In
+ | Operation::NotIn
+ | Operation::Regex
+ | Operation::NotRegex
+ | Operation::Iregex
+ | Operation::NotIregex
+ | Operation::GetProperty
+ | Operation::GetPropertyNullish => reduce(stack, 2),
+ Operation::Pop => {
+ pop(stack)?;
+ Ok(Control::Fall)
+ }
+ Operation::Return => {
+ pop(stack)?;
+ // The root frame's `RETURN` leaves nothing behind: the compiler emits one
+ // expression, and every scope pops its own locals first. Junk left here means a
+ // stack effect in the transfer table is wrong, and the next `GET_GLOBAL` would pop
+ // the wrong cells — so this turns a silent misread into a wide answer.
+ if stack.is_empty() {
+ Ok(Control::Terminate)
+ } else {
+ Err(Stop::Unanalyzable(UnanalyzableReason::UnbalancedReturn))
+ }
+ }
+ // `SET_PROPERTY` mutates the heap, which the model does not represent; the cohort
+ // opcodes read membership state that is not in the globals dict at all; the exception
+ // opcodes move the instruction pointer to a handler this pass does not track.
+ Operation::SetProperty
+ | Operation::InCohort
+ | Operation::NotInCohort
+ | Operation::Throw
+ | Operation::PopTry
+ | Operation::CloseUpvalue
+ | Operation::DeclareFn => Err(unsupported(op)),
+ // `decode` builds `Bare` only from the opcodes above.
+ other => Err(unsupported(other)),
+ }
+ }
+
+ /// `GET_GLOBAL` pops its path root first, because the compiler pushes the chain reversed.
+ fn get_global(&mut self, count: usize, stack: &mut AbstractStack) -> Result<Control, Stop> {
+ if count == 0 {
+ return Err(Stop::Unanalyzable(
+ UnanalyzableReason::ZeroLengthGlobalChain,
+ ));
+ }
+ // Checked before the allocation, not during the pops: `Vec::with_capacity` on an
+ // out-of-range count aborts the process rather than returning.
+ if count > stack.len() {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::StackUnderflow));
+ }
+ let mut chain = Vec::with_capacity(count);
+ for _ in 0..count {
+ match pop(stack)? {
+ AbstractValue::LiteralString(segment) => chain.push(segment),
+ AbstractValue::Opaque => {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::DynamicGlobalPath))
+ }
+ }
+ }
+ let (root_name, segments) = chain.split_first().expect("count is non-zero");
+ let Some(root) = GlobalRoot::parse(root_name) else {
+ return Err(Stop::Unanalyzable(UnanalyzableReason::UnknownGlobalRoot(
+ root_name.to_string(),
+ )));
+ };
+ // A bare `properties`, `person`, or `pdi` hands a whole object to whatever consumes it, so
+ // which keys are read is decided at runtime and cannot be narrowed here. `pdi` counts
+ // because the globals build it as a copy of the whole person tree.
+ if segments.is_empty() {
+ match root {
+ GlobalRoot::Properties => {
+ return Err(Stop::BareRoot(FullColumnsReason::BarePropertiesRoot))
+ }
+ GlobalRoot::Person | GlobalRoot::Pdi => {
+ return Err(Stop::BareRoot(FullColumnsReason::BarePersonRoot))
+ }
+ _ => {}
+ }
+ }
+ // `elements_chain` reads the event column, then falls back to this property when the column
+ // is empty. Both are real reads, so both are recorded or the claimed set would be short.
+ if root == GlobalRoot::ElementsChain {
+ self.reads.insert(ReadPath::new(
+ GlobalRoot::Properties,
+ vec![ELEMENTS_CHAIN_PROPERTY.to_owned()],
+ ));
+ }
+ let segments = segments.iter().map(|segment| segment.to_string()).collect();
+ self.reads.insert(ReadPath::new(root, segments));
+ push_opaque(stack)
+ }
+}
+
+fn branch(
+ op: Operation,
+ target: Option<TokenIndex>,
+ stack: &mut AbstractStack,
+) -> Result<Control, Stop> {
+ match op {
+ Operation::Jump => Ok(Control::Jump(target)),
+ // The condition is popped before the branch is taken, so both edges continue from the same
+ // stack.
+ Operation::JumpIfFalse => {
+ pop(stack)?;
+ Ok(Control::Fork(target))
+ }
+ // This one peeks and never pops, on either edge. On an empty stack the VM cannot read a
+ // top value, so it silently falls through — and modelling the jump anyway would merge two
+ // paths at different depths and fail a program the VM runs fine.
+ Operation::JumpIfStackNotNull => Ok(match stack.is_empty() {
+ true => Control::Fall,
+ false => Control::Fork(target),
+ }),
+ // `decode` builds `Branch` only from the opcodes above.
+ other => Err(unsupported(other)),
+ }
+}
+
+/// Consume `count` operands and leave one unnameable result.
+fn reduce(stack: &mut AbstractStack, count: usize) -> Result<Control, Stop> {
+ for _ in 0..count {
+ pop(stack)?;
+ }
+ push_opaque(stack)
+}
+
+fn push_opaque(stack: &mut AbstractStack) -> Result<Control, Stop> {
+ stack.push(AbstractValue::Opaque);
+ Ok(Control::Fall)
+}
+
+fn pop(stack: &mut AbstractStack) -> Result<AbstractValue, Stop> {
+ stack
+ .pop()
+ .ok_or(Stop::Unanalyzable(UnanalyzableReason::StackUnderflow))
+}
+
+fn unsupported(op: Operation) -> Stop {
+ Stop::Unanalyzable(UnanalyzableReason::UnsupportedOp(op))
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ fn program(tokens: Vec<Value>) -> Vec<Value> {
+ let mut bytecode = vec![json!("_H"), json!(1)];
+ bytecode.extend(tokens);
+ bytecode.push(json!(38));
+ bytecode
+ }
+
+ /// A global read, written the way the compiler emits it: the path is pushed leaf first so that
+ /// `GET_GLOBAL` pops the root first.
+ fn read(path: &[&str]) -> Vec<Value> {
+ let mut tokens = Vec::new();
+ for segment in path.iter().rev() {
+ tokens.push(json!(32));
+ tokens.push(json!(segment));
+ }
+ tokens.push(json!(1));
+ tokens.push(json!(path.len()));
+ tokens
+ }
+
+ fn reads(tokens: Vec<Value>) -> Vec<String> {
+ reads_of(&program(tokens))
+ }
+
+ fn reads_of(bytecode: &[Value]) -> Vec<String> {
+ match project(bytecode, &mut AnalysisBudget::for_one_condition()) {
+ Projection::Reads(paths) => paths.iter().map(ReadPath::render).collect(),
+ other => panic!("expected reads, got {other:?}"),
+ }
+ }
+
+ fn full_columns_reason(tokens: Vec<Value>) -> FullColumnsReason {
+ match project(&program(tokens), &mut AnalysisBudget::for_one_condition()) {
+ Projection::FullColumns(reason) => reason,
+ other => panic!("expected full columns, got {other:?}"),
+ }
+ }
+
+ fn unanalyzable_within(bytecode: &[Value], budget: &mut AnalysisBudget) -> UnanalyzableReason {
+ match project(bytecode, budget) {
+ Projection::FullColumns(FullColumnsReason::Unanalyzable(reason)) => reason,
+ other => panic!("expected an unanalyzable reason, got {other:?}"),
+ }
+ }
+
+ fn unanalyzable(tokens: Vec<Value>) -> UnanalyzableReason {
+ match full_columns_reason(tokens) {
+ FullColumnsReason::Unanalyzable(reason) => reason,
+ other => panic!("expected an unanalyzable reason, got {other:?}"),
+ }
+ }
+
+ /// The ordering test. The compiler pushes a chain reversed, so a reader that popped the leaf
+ /// first would record `key.properties` and project a column that does not exist. Written out
+ /// literally rather than through the helper, so the helper cannot hide the same mistake.
+ #[test]
+ fn a_global_chain_is_read_root_first_from_its_reversed_pushes() {
+ let tokens = vec![
+ json!(32),
+ json!("key"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ ];
+ assert_eq!(reads(tokens), ["properties.key"]);
+ }
+
+ #[test]
+ fn nested_paths_under_a_root_stay_precise() {
+ assert_eq!(
+ reads(read(&["person", "properties", "email"])),
+ ["person.properties.email"]
+ );
+ assert_eq!(reads(read(&["event"])), ["event"]);
+ assert_eq!(reads(read(&["pdi", "person_id"])), ["pdi.person_id"]);
+ assert_eq!(
+ reads(read(&["group_2", "properties", "tier"])),
+ ["group_2.properties.tier"]
+ );
+ }
+
+ /// Handing a whole `properties`, `person`, or `pdi` object to something decides its keys at
+ /// runtime. These are ordinary programs, so they are reported as bare roots rather than as
+ /// failures. `pdi` is a copy of the whole person tree, so a claimed read of it alone would look
+ /// narrow while needing every person column.
+ #[test]
+ fn a_bare_object_root_widens_to_every_column() {
+ assert_eq!(
+ full_columns_reason(read(&["properties"])),
+ FullColumnsReason::BarePropertiesRoot
+ );
+ assert_eq!(
+ full_columns_reason(read(&["person"])),
+ FullColumnsReason::BarePersonRoot
+ );
+ assert_eq!(
+ full_columns_reason(read(&["pdi"])),
+ FullColumnsReason::BarePersonRoot
+ );
+ }
+
+ /// `elements_chain` resolves to the event column or, when that is empty, to
+ /// `properties.$elements_chain`. A claimed read set that named only the column would be short,
+ /// and a caller projecting from it would evaluate the condition against a null chain.
+ #[test]
+ fn an_elements_chain_read_also_claims_its_properties_fallback() {
+ assert_eq!(
+ reads(read(&["elements_chain"])),
+ ["elements_chain", "properties.$elements_chain"]
+ );
+ // The sibling roots are constants in the globals, independent of the event, so they claim
+ // nothing extra.
+ assert_eq!(
+ reads(read(&["elements_chain_texts"])),
+ ["elements_chain_texts"]
+ );
+ }
+
+ #[test]
+ fn several_reads_under_one_program_are_collected_and_deduplicated() {
+ let mut tokens = read(&["properties", "b"]);
+ tokens.extend(read(&["properties", "a"]));
+ tokens.extend(read(&["properties", "b"]));
+ tokens.push(json!(3));
+ tokens.push(json!(3));
+ assert_eq!(reads(tokens), ["properties.a", "properties.b"]);
+ }
+
+ /// A path segment computed at runtime, an unmodeled root, an unmodeled opcode, and garbage all
+ /// have to fail closed, each naming what stopped the analysis.
+ #[test]
+ fn unmodeled_programs_fail_closed_with_their_reason() {
+ // `properties[someValue]`: the segment on the stack is not a literal.
+ let dynamic = vec![
+ json!(33),
+ json!(3),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ ];
+ assert_eq!(unanalyzable(dynamic), UnanalyzableReason::DynamicGlobalPath);
+ assert_eq!(
+ unanalyzable(read(&["session"])),
+ UnanalyzableReason::UnknownGlobalRoot("session".to_owned())
+ );
+ assert_eq!(
+ unanalyzable(vec![json!(1), json!(0)]),
+ UnanalyzableReason::ZeroLengthGlobalChain
+ );
+ // A `TRY` installs a handler this pass does not follow.
+ assert_eq!(
+ unanalyzable(vec![json!(50), json!(1), json!(29)]),
+ UnanalyzableReason::UnsupportedOp(Operation::Try)
+ );
+ assert_eq!(
+ unanalyzable(vec![json!(11)]),
+ UnanalyzableReason::StackUnderflow
+ );
+ assert!(matches!(
+ unanalyzable(vec![json!(99)]),
+ UnanalyzableReason::Decode(_)
+ ));
+ }
+
+ /// The `if(cond, a, b)` shape the compiler emits for `null_safe_comparisons`. Both arms are
+ /// visited, so a read reachable on either one is claimed. Refusing the branch — as the linear
+ /// model did — reported every `>`/`>=`/`<`/`<=` condition as unreadable.
+ #[test]
+ fn both_arms_of_a_conditional_contribute_their_reads() {
+ // if(<opaque>, properties.a, properties.b)
+ let then = read(&["properties", "a"]);
+ let otherwise = read(&["properties", "b"]);
+ let mut tokens = vec![json!(29)];
+ tokens.push(json!(40));
+ tokens.push(json!(then.len() as i64 + 2));
+ tokens.extend(then);
+ tokens.push(json!(39));
+ tokens.push(json!(otherwise.len() as i64));
+ tokens.extend(otherwise);
+ assert_eq!(reads(tokens), ["properties.a", "properties.b"]);
+ }
+
+ /// The `ifNull(expr, fallback)` shape, which wraps every regex comparison. The peek does not
+ /// pop, and the fall-through arm's `POP` is what balances it, so the two paths meet at the
+ /// same depth.
+ #[test]
+ fn an_ifnull_peek_and_its_pop_arm_meet_at_the_same_depth() {
+ let mut tokens = read(&["properties", "url"]);
+ // JUMP_IF_STACK_NOT_NULL over the POP and the FALSE that replaces the null.
+ tokens.push(json!(47));
+ tokens.push(json!(2));
+ tokens.push(json!(35));
+ tokens.push(json!(30));
+ assert_eq!(reads(tokens), ["properties.url"]);
+ }
+
+ /// The `between` lowering: an IIFE that keeps its operands in local slots, reads them back with
+ /// `GET_LOCAL`, merges two arms, and pops the locals on the way out. The whole shape has to
+ /// stay readable, because a date range is one of the commonest cohort conditions.
+ #[test]
+ fn a_between_iife_over_local_slots_stays_readable() {
+ // NULL (result slot), then the three operands into slots 1-3.
+ let mut tokens = vec![json!(31)];
+ tokens.extend(read(&["properties", "score"]));
+ tokens.push(json!(33));
+ tokens.push(json!(1));
+ tokens.push(json!(33));
+ tokens.push(json!(10));
+ // low != null AND high != null AND expr != null
+ for slot in [2, 3, 1] {
+ tokens.push(json!(36));
+ tokens.push(json!(slot));
+ tokens.push(json!(31));
+ tokens.push(json!(12));
+ }
+ tokens.push(json!(3));
+ tokens.push(json!(3));
+ // expr >= low AND expr <= high
+ let between = vec![
+ json!(36),
+ json!(2),
+ json!(36),
+ json!(1),
+ json!(14),
+ json!(36),
+ json!(3),
+ json!(36),
+ json!(1),
+ json!(16),
+ json!(3),
+ json!(2),
+ ];
+ tokens.push(json!(40));
+ tokens.push(json!(between.len() as i64 + 2));
+ tokens.extend(between);
+ tokens.push(json!(39));
+ tokens.push(json!(1));
+ tokens.push(json!(30));
+ // Store into the result slot, then pop the three locals.
+ tokens.push(json!(37));
+ tokens.push(json!(0));
+ tokens.extend([json!(35), json!(35), json!(35)]);
+ assert_eq!(reads(tokens), ["properties.score"]);
+ }
+
+ /// A backward jump makes the worklist revisit instructions until the joined stacks stop
+ /// changing. Without a fixpoint this would either loop forever or report a program the VM runs.
+ #[test]
+ fn a_backward_jump_converges_on_a_fixpoint() {
+ // properties.a; loop: POP; properties.b; JUMP back to loop.
+ let mut tokens = read(&["properties", "a"]);
+ let loop_body_len: i64 = 1 + read(&["properties", "b"]).len() as i64;
+ tokens.push(json!(35));
+ tokens.extend(read(&["properties", "b"]));
+ tokens.push(json!(39));
+ tokens.push(json!(-(loop_body_len + 2)));
+ assert_eq!(reads(tokens), ["properties.a", "properties.b"]);
+ }
+
+ /// Two paths that meet holding different stack depths mean the transfer table has lost the
+ /// layout, and every later `GET_GLOBAL` would pop the wrong cells.
+ #[test]
+ fn paths_meeting_at_different_depths_fail_closed() {
+ // TRUE; JUMP_IF_FALSE over one push; TRUE; (merge) — the taken edge arrives one shallower.
+ let tokens = vec![json!(29), json!(40), json!(1), json!(29)];
+ assert_eq!(unanalyzable(tokens), UnanalyzableReason::StackDepthMismatch);
+ }
+
+ /// A jump into the middle of an instruction would have the VM read an immediate as an opcode.
+ /// Landing one past the last token is different: that is a jump off the end, and the program
+ /// simply stops there.
+ #[test]
+ fn a_jump_off_a_boundary_fails_closed_but_a_jump_off_the_end_terminates() {
+ // JUMP into the middle of the following STRING instruction.
+ assert_eq!(
+ unanalyzable(vec![json!(39), json!(1), json!(32), json!("x"), json!(35)]),
+ UnanalyzableReason::BadJumpTarget
+ );
+ // JUMP past `program`'s trailing RETURN, which is one token past the end.
+ assert_eq!(
+ unanalyzable(vec![json!(39), json!(99)]),
+ UnanalyzableReason::BadJumpTarget
+ );
+ // A read, then a jump that lands exactly on the end: the read still counts.
+ let mut off_the_end = read(&["event"]);
+ off_the_end.push(json!(35));
+ off_the_end.push(json!(39));
+ off_the_end.push(json!(1));
+ assert_eq!(reads(off_the_end), ["event"]);
+ }
+
+ /// A local slot outside the frame is what the VM's own bounds check refuses, so the analysis
+ /// must not silently read or write a cell that is not there.
+ #[test]
+ fn a_local_slot_outside_the_frame_fails_closed() {
+ assert_eq!(
+ unanalyzable(vec![json!(36), json!(3), json!(29)]),
+ UnanalyzableReason::LocalSlotOutOfRange
+ );
+ assert_eq!(
+ unanalyzable(vec![json!(29), json!(37), json!(4)]),
+ UnanalyzableReason::LocalSlotOutOfRange
+ );
+ }
+
+ /// A `RETURN` that leaves values behind means a stack effect in the transfer table is wrong.
+ /// Reporting it turns a class of silent misreads into a wide, safe answer.
+ #[test]
+ fn a_return_over_an_unbalanced_stack_fails_closed() {
+ assert_eq!(
+ unanalyzable(vec![json!(29), json!(29)]),
+ UnanalyzableReason::UnbalancedReturn
+ );
+ }
+
+ /// The loader appends a `RETURN` to bytecode that may already end in one, so a repeated
+ /// trailing `RETURN` is normal: the first one terminates every path, and the second is simply
+ /// never reached.
+ #[test]
+ fn a_repeated_trailing_return_is_never_reached() {
+ assert_eq!(reads(read(&["event"])), ["event"]);
+ }
+
+ /// A long straight-line program has no merge point, so the pass stores no per-instruction
+ /// state at all.
+ ///
+ /// This is the shape a large `IN` list compiles to, and catalogs hold lists of several
+ /// thousand. Storing one abstract stack per instruction across such a program is cells
+ /// proportional to the square of its length: at the largest list size production is known to
+ /// carry, that was over a gigabyte and seconds of blocking on the caller's task, for a program
+ /// the VM itself evaluates in kilobytes.
+ #[test]
+ fn a_long_straight_line_program_costs_no_stored_state() {
+ const ELEMENTS: usize = 2_000;
+ let mut tokens = Vec::new();
+ for index in 0..ELEMENTS {
+ tokens.push(json!(32));
+ tokens.push(json!(format!("v{index}")));
+ }
+ tokens.push(json!(44));
+ tokens.push(json!(ELEMENTS));
+ tokens.extend(read(&["properties", "plan"]));
+ tokens.push(json!(21));
+
+ let bytecode = program(tokens);
+ let decoded = decode(&bytecode).expect("an IN list decodes");
+ let starts: Vec<TokenIndex> = decoded.instrs.iter().map(|instr| instr.start).collect();
+ assert!(
+ !merge_points(&decoded, &starts).contains(&true),
+ "an IN list has a merge point, so the pass would store one stack per instruction"
+ );
+ assert_eq!(reads_of(&bytecode), ["properties.plan"]);
+ }
+
+ /// A jump the decoder could not resolve is refused where it is visited, not where it is read.
+ /// A dead one costs nothing, which is the same rule every other unmodeled construct follows.
+ #[test]
+ fn an_unresolvable_jump_fails_closed_only_when_a_path_reaches_it() {
+ assert_eq!(
+ unanalyzable(vec![json!(39), json!(-99)]),
+ UnanalyzableReason::BadJumpTarget
+ );
+ // The same jump, behind an unconditional jump over it.
+ let mut tokens = read(&["properties", "plan"]);
+ tokens.push(json!(39));
+ tokens.push(json!(2));
+ tokens.push(json!(39));
+ tokens.push(json!(-99));
+ assert_eq!(reads(tokens), ["properties.plan"]);
+ }
+
+ /// Refusal happens when an instruction is visited, so an unmodeled opcode no path reaches costs
+ /// nothing. Without that, one dead `CALLABLE` would widen an otherwise readable condition.
+ #[test]
+ fn an_unmodeled_opcode_no_path_reaches_is_harmless() {
+ let mut tokens = read(&["properties", "plan"]);
+ tokens.push(json!(39));
+ // Jump over a CALLABLE with an empty body.
+ tokens.push(json!(5));
+ tokens.extend([json!(52), json!("f"), json!(0), json!(0), json!(0)]);
+ assert_eq!(reads(tokens), ["properties.plan"]);
+ }
+
+ /// A native call is projection-safe whatever its name, because it only consumes stack values.
+ /// Refusing them would make every `toDateTime(timestamp) > x` condition unprojectable.
+ #[test]
+ fn a_native_call_over_a_read_keeps_the_read_precise() {
+ let mut tokens = read(&["timestamp"]);
+ tokens.push(json!(2));
+ tokens.push(json!("toDateTime"));
+ tokens.push(json!(1));
+ tokens.push(json!(32));
+ tokens.push(json!("2026-01-01"));
+ tokens.push(json!(13));
+ assert_eq!(reads(tokens), ["timestamp"]);
+ }
+
+ /// A hostile count immediate must not reach an allocation. `u64::MAX` is a capacity-overflow
+ /// panic and a merely huge value is an allocation abort; either would take down the caller's
+ /// task, which the fail-closed contract cannot absorb.
+ ///
+ /// The refusal also names the opcode it stopped on. A decode failure is the reason a census
+ /// cannot diagnose from the coarse label alone, because it is what a decoder drifting from
+ /// `vm.rs` looks like, and the opcode is the field that says which table entry drifted.
+ #[test]
+ fn a_hostile_global_chain_count_never_allocates() {
+ for count in [json!(u64::MAX), json!(4_000_000_000u64)] {
+ let reason = unanalyzable(vec![json!(1), count.clone()]);
+ assert!(matches!(reason, UnanalyzableReason::Decode(_)));
+ assert_eq!(reason.op(), Some(Operation::GetGlobal));
+ }
+ // A count the decoder accepts, still deeper than the stack.
+ let padded = std::iter::repeat_n(json!(29), 8)
+ .chain([json!(1), json!(6)])
+ .collect::<Vec<_>>();
+ assert_eq!(
+ unanalyzable(padded),
+ UnanalyzableReason::DynamicGlobalPath,
+ "eight opaque pushes are enough for a six-deep chain, so this is not an underflow"
+ );
+ let shallow = vec![json!(29), json!(29), json!(1), json!(6)];
+ assert_eq!(unanalyzable(shallow), UnanalyzableReason::StackUnderflow);
+ }
+
+ /// Both ceilings, on programs small enough to reach them at unit cost rather than at a million
+ /// steps. They are guards rather than dead code, so the risk they carry is not an unreachable
+ /// branch — it is a guard that is wrong and nothing that says so.
+ ///
+ /// The step ceiling is reached through the loop here rather than through the spent-budget
+ /// shortcut, which the next test covers.
+ #[test]
+ fn each_ceiling_fails_closed_under_its_own_reason() {
+ // STRING, STRING, GET_GLOBAL, RETURN.
+ let straight_line = program(read(&["properties", "plan"]));
+ assert_eq!(
+ unanalyzable_within(
+ &straight_line,
+ &mut AnalysisBudget {
+ steps: 1,
+ cells: usize::MAX
+ }
+ ),
+ UnanalyzableReason::IterationBudget
+ );
+
+ // A fork whose two edges both land on the POP, so the pass copies its one-deep stack onto
+ // the worklist rather than walking it in place. Without a copy there is no cell to charge.
+ let forked = program(vec![
+ json!(32),
+ json!("x"),
+ json!(29),
+ json!(40),
+ json!(0),
+ json!(35),
+ json!(29),
+ ]);
+ assert_eq!(
+ reads_of(&forked),
+ Vec::<String>::new(),
+ "the fork analyzes cleanly when the budget allows it"
+ );
+ assert_eq!(
+ unanalyzable_within(
+ &forked,
+ &mut AnalysisBudget {
+ steps: usize::MAX,
+ cells: 0
+ }
+ ),
+ UnanalyzableReason::StateBudget
+ );
+ }
+
+ /// One budget across several conditions is what bounds a batch rather than each member of it.
+ /// The spend has to be real: a budget that reset per condition would leave `conditions ×
+ /// ceiling`, which is the shape this exists to refuse.
+ #[test]
+ fn a_shared_budget_is_spent_down_and_then_refuses() {
+ // STRING, STRING, GET_GLOBAL, RETURN: four transfer steps, exactly.
+ let bytecode = program(read(&["properties", "plan"]));
+ let mut budget = AnalysisBudget {
+ steps: 4,
+ cells: usize::MAX,
+ };
+ assert!(matches!(
+ project(&bytecode, &mut budget),
+ Projection::Reads(_)
+ ));
+ assert_eq!(budget.steps, 0);
+ // The next condition is refused before it is even decoded.
+ assert_eq!(
+ unanalyzable_within(&bytecode, &mut budget),
+ UnanalyzableReason::IterationBudget
+ );
+ }
+
+ /// A deep stack, then diamonds whose two arms write different literals into one local slot, so
+ /// every rejoin widens a cell and re-enqueues a full-depth stack.
+ fn widening_diamonds(depth: usize, count: usize) -> Vec<Value> {
+ let mut tokens = Vec::new();
+ for index in 0..depth {
+ tokens.push(json!(32));
+ tokens.push(json!(format!("v{index}")));
+ }
+ for index in 0..count {
+ let slot = index % depth;
+ // TRUE; JUMP_IF_FALSE over the first arm.
+ tokens.extend([json!(29), json!(40), json!(6)]);
+ // STRING "a"; SET_LOCAL slot; JUMP over the second arm.
+ tokens.extend([
+ json!(32),
+ json!("a"),
+ json!(37),
+ json!(slot),
+ json!(39),
+ json!(4),
+ ]);
+ // STRING "b"; SET_LOCAL slot.
+ tokens.extend([json!(32), json!("b"), json!(37), json!(slot)]);
+ }
+ for _ in 0..depth {
+ tokens.push(json!(35));
+ }
+ tokens.push(json!(31));
+ tokens
+ }
+
+ /// The shape merge-point gating does not answer: a program that is *all* merge points.
+ ///
+ /// Its cost is the copying, and neither of the other two ceilings sees it. Steps do not, because
+ /// one step copies a whole stack. The memory ceiling does not either, because each copy is
+ /// popped again, so the pass holds a fraction of what it has copied. At the sizes a catalog row
+ /// can carry this ran for over a second on the caller's task before the copied-cell ceiling
+ /// existed.
+ #[test]
+ fn a_program_that_is_all_merge_points_is_charged_by_the_cells_it_copies() {
+ let bytecode = program(widening_diamonds(40, 40));
+ let decoded = decode(&bytecode).expect("the shape decodes");
+ let mut interpreter = Interpreter::new(&decoded, AnalysisBudget::for_one_condition());
+ interpreter
+ .run()
+ .unwrap_or_else(|_| panic!("the shape analyzes cleanly under a whole budget"));
+ assert!(
+ interpreter.cells_copied > interpreter.steps * 5,
+ "{} steps against {} copied cells, so the step ceiling bounds this shape after all",
+ interpreter.steps,
+ interpreter.cells_copied
+ );
+ assert!(
+ interpreter.retained < MAX_RETAINED_CELLS / 10,
+ "{} cells held at the end, so the memory ceiling is what bounds this shape",
+ interpreter.retained
+ );
+
+ assert_eq!(
+ unanalyzable_within(
+ &bytecode,
+ &mut AnalysisBudget {
+ steps: usize::MAX,
+ cells: 1_000
+ }
+ ),
+ UnanalyzableReason::StateBudget
+ );
+ }
+}
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
index 78bb8a17c024..b85ebdefffee 100644
--- a/rust/cohort-core/src/hogvm/mod.rs
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -10,6 +10,7 @@
//! is bring-your-own-metrics: it emits nothing and hands the caller the classified outcome. The
//! seeder uses it so failures land on its own `seeder_hogvm_*` counters, not these.
+pub mod analysis;
mod executor;
mod globals;
diff --git a/rust/cohort-core/tests/analysis_corpus.rs b/rust/cohort-core/tests/analysis_corpus.rs
new file mode 100644
index 000000000000..263c62b285cd
--- /dev/null
+++ b/rust/cohort-core/tests/analysis_corpus.rs
@@ -0,0 +1,72 @@
+//! Runs the shared HogVM bytecode corpus through the static analysis, as a totality check.
+//!
+//! The corpus is general Hog — closures, locals, exception handling — not cohort filters, and none
+//! of its programs touch the globals dict. So this asserts one thing: that the analysis terminates
+//! with an answer on arbitrary real bytecode. A panic or a hang is what would break the seeder,
+//! because the analysis runs on every condition at run-validation time.
+//!
+//! It is deliberately not a coverage corpus, and cannot be read as one. Whether the analysis names
+//! the right globals for a *cohort* condition is `analysis_parity_corpus.rs`'s question, over
+//! compiled cohort bytecode with a recorded oracle verdict.
+
+use cohort_core::hogvm::analysis::{analyze_condition, ConditionAnalysis, Projection, ReadPath};
+use serde_json::Value;
+
+const CORPUS: &str = include_str!("../../common/hogvm/tests/static/bytecode_examples.jsonl");
+
+fn corpus() -> Vec<Vec<Value>> {
+ CORPUS
+ .lines()
+ .filter(|line| !line.trim().is_empty())
+ .map(|line| serde_json::from_str(line).expect("the shared corpus is valid JSON"))
+ .collect()
+}
+
+#[test]
+fn the_shared_corpus_analyzes_without_panicking() {
+ let programs = corpus();
+ assert!(
+ programs.len() >= 30,
+ "the corpus shrank to {} programs; this test would stop covering anything",
+ programs.len()
+ );
+ for program in &programs {
+ analyze_condition(program);
+ }
+}
+
+#[test]
+fn analyzing_the_same_program_twice_gives_the_same_answer() {
+ for program in corpus() {
+ assert_eq!(
+ analyze_condition(&program),
+ analyze_condition(&program),
+ "analysis of {program:?} is not deterministic"
+ );
+ }
+}
+
+/// No corpus program names a global it reads.
+///
+/// The corpus is general Hog, so its programs split two ways. Most use closures or exception
+/// handling, which the model refuses, and land on full columns. The rest are string-function
+/// demonstrations over literals with no `GET_GLOBAL` at all, and those correctly read nothing. What
+/// no program in this corpus can legitimately produce is a read of a named global, because none of
+/// them touch the globals dict. A change that started reporting one here would be inventing reads.
+#[test]
+fn no_general_hog_program_claims_to_read_a_named_global() {
+ for program in corpus() {
+ let ConditionAnalysis {
+ projection: Projection::Reads(paths),
+ ..
+ } = analyze_condition(&program)
+ else {
+ continue;
+ };
+ assert!(
+ paths.is_empty(),
+ "a corpus program that reads no globals claimed {:?}",
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>()
+ );
+ }
+}
diff --git a/rust/cohort-core/tests/analysis_equivalence.proptest-regressions b/rust/cohort-core/tests/analysis_equivalence.proptest-regressions
new file mode 100644
index 000000000000..c51fa1bdd5ca
--- /dev/null
+++ b/rust/cohort-core/tests/analysis_equivalence.proptest-regressions
@@ -0,0 +1,7 @@
+# Seeds for failure cases proptest has generated in the past. It is
+# automatically read and these particular cases re-run before any
+# novel cases are generated.
+#
+# It is recommended to check this file in to source control so that
+# everyone who runs the test benefits from these saved cases.
+cc 572ecd734bcb50bbe0ed22d463e152594e88e43a0747f7e49a132a47a1dc68fe # shrinks to expr = Any([All([Compare { field: ElementsChain, op: Gt, literal: "alpha" }])]), event = TestEvent { event: "purchase", distinct_id: "alpha", timestamp: "2026-05-26 12:34:56.789000", elements_chain: "", properties: {"$browser": "noise", "$elements_chain": "a:href=\"/alpha\"", "$os": "noise", "country": "alpha", "plan": "alpha", "tier": "alpha", "unrelated": "noise"}, person_properties: {"email": "alpha", "role": "alpha"} }
diff --git a/rust/cohort-core/tests/analysis_equivalence.rs b/rust/cohort-core/tests/analysis_equivalence.rs
new file mode 100644
index 000000000000..cfb8d89311c5
--- /dev/null
+++ b/rust/cohort-core/tests/analysis_equivalence.rs
@@ -0,0 +1,807 @@
+//! The gate on [`cohort_core::hogvm::analysis`]: a condition evaluated against only the globals the
+//! analysis claimed it reads must reach the same verdict as one evaluated against the whole event.
+//!
+//! That is the property a caller relies on. If the claimed read set were ever short, a scan built
+//! from it would hand the VM an event missing a value the condition needs, and the condition would
+//! quietly decide the wrong way. Per-opcode unit tests cannot catch that, because the failure is a
+//! disagreement between two whole evaluations rather than a wrong step.
+//!
+//! Every program here is synthesized from an AST by an emitter that mirrors the HogQL compiler's
+//! output order. No bytecode is copied from a real catalog.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use cohort_core::events::CohortStreamEvent;
+use cohort_core::hogvm::analysis::{analyze_condition, GlobalRoot, Projection, ReadPath};
+use cohort_core::{build_behavioral_globals, evaluate_detailed, EvalOutcome};
+use proptest::prelude::*;
+use serde_json::{json, Value};
+
+// Opcodes, named so the emitter reads like the compiler's output.
+const OP_GET_GLOBAL: i64 = 1;
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_AND: i64 = 3;
+const OP_OR: i64 = 4;
+const OP_NOT_EQ: i64 = 12;
+const OP_GT_EQ: i64 = 14;
+const OP_LT_EQ: i64 = 16;
+const OP_FALSE: i64 = 30;
+const OP_NULL: i64 = 31;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_POP: i64 = 35;
+const OP_GET_LOCAL: i64 = 36;
+const OP_SET_LOCAL: i64 = 37;
+const OP_RETURN: i64 = 38;
+const OP_JUMP: i64 = 39;
+const OP_JUMP_IF_FALSE: i64 = 40;
+const OP_TUPLE: i64 = 44;
+const OP_JUMP_IF_STACK_NOT_NULL: i64 = 47;
+
+/// A property key no generated condition ever reads. Every event carries it, so a projection that
+/// leaked the whole property bag instead of the claimed keys would still pass; a projection that
+/// dropped a claimed key would not.
+const NOISE_KEYS: [&str; 3] = ["$browser", "$os", "unrelated"];
+
+/// The property the globals fall back to when the elements-chain column is empty.
+const ELEMENTS_CHAIN_PROPERTY: &str = "$elements_chain";
+
+/// The event globals a generated condition may compare against.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Field {
+ Event,
+ DistinctId,
+ Timestamp,
+ ElementsChain,
+ Property(String),
+ PersonProperty(String),
+}
+
+impl Field {
+ /// The global chain, root first, as HogQL would write it.
+ fn chain(&self) -> Vec<&str> {
+ match self {
+ Self::Event => vec!["event"],
+ Self::DistinctId => vec!["distinct_id"],
+ Self::Timestamp => vec!["timestamp"],
+ Self::ElementsChain => vec!["elements_chain"],
+ Self::Property(key) => vec!["properties", key],
+ Self::PersonProperty(key) => vec!["person", "properties", key],
+ }
+ }
+}
+
+/// The comparison opcodes a cohort condition realistically compiles to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CmpOp {
+ Eq = 11,
+ NotEq = 12,
+ Gt = 13,
+ GtEq = 14,
+ Lt = 15,
+ LtEq = 16,
+ Like = 17,
+ ILike = 18,
+ Regex = 23,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Expr {
+ Compare {
+ field: Field,
+ op: CmpOp,
+ literal: String,
+ },
+ /// `if(isNull(left) or isNull(right), false, left <op> right)`, which is what
+ /// `null_safe_comparisons` turns every `>`, `>=`, `<`, and `<=` into. The cohort API compiles
+ /// with that flag on, so this — not [`Expr::Compare`] — is the shape a date or numeric filter
+ /// actually reaches the seeder as.
+ NullSafeCompare {
+ field: Field,
+ op: CmpOp,
+ literal: String,
+ },
+ /// `ifNull(match(toString(field), pattern), 0)`, how `property.py` compiles a regex filter. The
+ /// `ifNull` lowers to a `JUMP_IF_STACK_NOT_NULL`/`POP` pair, and the two nested calls put
+ /// `CALL_GLOBAL` under the equivalence check rather than under a read-set assertion alone.
+ IfNullRegex {
+ field: Field,
+ pattern: String,
+ },
+ InTuple {
+ field: Field,
+ options: Vec<String>,
+ },
+ All(Vec<Expr>),
+ Any(Vec<Expr>),
+}
+
+/// `field BETWEEN low AND high`, which compiles to an IIFE holding its three operands in local
+/// slots and merging two arms into a result slot.
+///
+/// Kept out of [`Expr`] because the compiler numbers those slots from the frame base, so the shape
+/// is only faithful at the top level of a program. Nesting it inside an `AND` would emit slot
+/// numbers that no longer line up with the stack, which would test the harness's guess rather than
+/// the compiler's output.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct Between {
+ field: Field,
+ low: i64,
+ high: i64,
+}
+
+/// Emit `expr` the way `posthog/hogql/compiler/bytecode.py` emits it.
+///
+/// Two orderings are load-bearing and are the reason this emitter exists rather than a hand-written
+/// fixture. A comparison emits its right operand first, then its left, then the opcode. A global
+/// chain is pushed leaf first, so `GET_GLOBAL` pops the root first.
+fn emit(expr: &Expr) -> Vec<Value> {
+ match expr {
+ Expr::Compare { field, op, literal } => {
+ let mut tokens = vec![json!(OP_STRING), json!(literal)];
+ tokens.extend(emit_field(field));
+ tokens.push(json!(*op as i64));
+ tokens
+ }
+ Expr::InTuple { field, options } => {
+ let mut tokens = Vec::new();
+ for option in options {
+ tokens.push(json!(OP_STRING));
+ tokens.push(json!(option));
+ }
+ tokens.push(json!(OP_TUPLE));
+ tokens.push(json!(options.len()));
+ tokens.extend(emit_field(field));
+ tokens.push(json!(21));
+ tokens
+ }
+ Expr::NullSafeCompare { field, op, literal } => {
+ // `or(isNull(left), isNull(right))`, then the `if` that guards the real comparison.
+ let mut tokens = emit_field(field);
+ tokens.extend(emit_call("isNull", 1));
+ tokens.push(json!(OP_STRING));
+ tokens.push(json!(literal));
+ tokens.extend(emit_call("isNull", 1));
+ tokens.push(json!(OP_OR));
+ tokens.push(json!(2));
+
+ let comparison = emit(&Expr::Compare {
+ field: field.clone(),
+ op: *op,
+ literal: literal.clone(),
+ });
+ // The `then` arm is one `FALSE` token, plus the two the `JUMP` over the else takes.
+ tokens.push(json!(OP_JUMP_IF_FALSE));
+ tokens.push(json!(3));
+ tokens.push(json!(OP_FALSE));
+ tokens.push(json!(OP_JUMP));
+ tokens.push(json!(comparison.len() as i64));
+ tokens.extend(comparison);
+ tokens
+ }
+ Expr::IfNullRegex { field, pattern } => {
+ let mut tokens = emit_field(field);
+ tokens.extend(emit_call("toString", 1));
+ tokens.push(json!(OP_STRING));
+ tokens.push(json!(pattern));
+ tokens.extend(emit_call("match", 2));
+ // The null arm is `INTEGER 0`, two tokens, plus the `POP` the jump also skips.
+ tokens.push(json!(OP_JUMP_IF_STACK_NOT_NULL));
+ tokens.push(json!(3));
+ tokens.push(json!(OP_POP));
+ tokens.push(json!(OP_INTEGER));
+ tokens.push(json!(0));
+ tokens
+ }
+ Expr::All(exprs) => emit_combined(exprs, OP_AND),
+ Expr::Any(exprs) => emit_combined(exprs, OP_OR),
+ }
+}
+
+fn emit_call(name: &str, argc: i64) -> Vec<Value> {
+ vec![json!(OP_CALL_GLOBAL), json!(name), json!(argc)]
+}
+
+/// Emit `field BETWEEN low AND high` exactly as `visit_between_expr` does: push a `NULL` result
+/// slot, then the three operands into slots 1-3, null-check them through `GET_LOCAL`, branch, store
+/// the answer into slot 0, and pop the three locals on the way out.
+fn emit_between(between: &Between) -> Vec<Value> {
+ let Between { field, low, high } = between;
+ let mut tokens = vec![json!(OP_NULL)];
+ tokens.extend(emit_field(field));
+ tokens.extend([json!(OP_INTEGER), json!(low)]);
+ tokens.extend([json!(OP_INTEGER), json!(high)]);
+
+ // low != null AND high != null AND expr != null
+ for slot in [2, 3, 1] {
+ tokens.extend([
+ json!(OP_GET_LOCAL),
+ json!(slot),
+ json!(OP_NULL),
+ json!(OP_NOT_EQ),
+ ]);
+ }
+ tokens.extend([json!(OP_AND), json!(3)]);
+
+ // expr >= low AND expr <= high
+ let comparison = vec![
+ json!(OP_GET_LOCAL),
+ json!(2),
+ json!(OP_GET_LOCAL),
+ json!(1),
+ json!(OP_GT_EQ),
+ json!(OP_GET_LOCAL),
+ json!(3),
+ json!(OP_GET_LOCAL),
+ json!(1),
+ json!(OP_LT_EQ),
+ json!(OP_AND),
+ json!(2),
+ ];
+ tokens.push(json!(OP_JUMP_IF_FALSE));
+ tokens.push(json!(comparison.len() as i64 + 2));
+ tokens.extend(comparison);
+ tokens.extend([json!(OP_JUMP), json!(1), json!(OP_FALSE)]);
+ tokens.extend([json!(OP_SET_LOCAL), json!(0)]);
+ tokens.extend([json!(OP_POP), json!(OP_POP), json!(OP_POP)]);
+ tokens
+}
+
+fn emit_combined(exprs: &[Expr], op: i64) -> Vec<Value> {
+ let mut tokens = Vec::new();
+ for expr in exprs {
+ tokens.extend(emit(expr));
+ }
+ tokens.push(json!(op));
+ tokens.push(json!(exprs.len()));
+ tokens
+}
+
+fn emit_field(field: &Field) -> Vec<Value> {
+ let chain = field.chain();
+ let mut tokens = Vec::new();
+ for segment in chain.iter().rev() {
+ tokens.push(json!(OP_STRING));
+ tokens.push(json!(segment));
+ }
+ tokens.push(json!(OP_GET_GLOBAL));
+ tokens.push(json!(chain.len()));
+ tokens
+}
+
+/// The loaded form: the header, the program, and the `RETURN` the catalog loader appends.
+fn program(expr: &Expr) -> Vec<Value> {
+ loaded(emit(expr))
+}
+
+fn loaded(body: Vec<Value>) -> Vec<Value> {
+ let mut bytecode = vec![json!("_H"), json!(1)];
+ bytecode.extend(body);
+ bytecode.push(json!(OP_RETURN));
+ bytecode
+}
+
+/// A generated event. Held as fields rather than as built globals so it can be projected.
+#[derive(Debug, Clone)]
+struct TestEvent {
+ event: String,
+ distinct_id: String,
+ timestamp: String,
+ elements_chain: String,
+ properties: BTreeMap<String, String>,
+ person_properties: BTreeMap<String, String>,
+}
+
+impl TestEvent {
+ fn to_stream_event(&self) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: 2,
+ person_id: "01931234-0000-0000-0000-000000000001".to_owned(),
+ distinct_id: self.distinct_id.clone(),
+ uuid: "01931234-0000-0000-0000-0000000000ff".to_owned(),
+ event: self.event.clone(),
+ timestamp: self.timestamp.clone(),
+ properties: Some(to_json_object(&self.properties)),
+ person_properties: Some(to_json_object(&self.person_properties)),
+ elements_chain: (!self.elements_chain.is_empty()).then(|| self.elements_chain.clone()),
+ source_offset: 0,
+ source_partition: -1,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+ }
+
+ /// The event a scan built from `paths` would produce: everything the analysis did not claim is
+ /// absent, exactly as a narrower `SELECT` would leave it.
+ fn projected(&self, paths: &BTreeSet<ReadPath>) -> CohortStreamEvent {
+ let mut projected = TestEvent {
+ event: String::new(),
+ distinct_id: String::new(),
+ timestamp: String::new(),
+ elements_chain: String::new(),
+ properties: BTreeMap::new(),
+ person_properties: BTreeMap::new(),
+ };
+ for path in paths {
+ match (&path.root, path.segments.as_slice()) {
+ (GlobalRoot::Event, []) => projected.event = self.event.clone(),
+ (GlobalRoot::DistinctId, []) => projected.distinct_id = self.distinct_id.clone(),
+ (GlobalRoot::Timestamp, []) => projected.timestamp = self.timestamp.clone(),
+ (GlobalRoot::ElementsChain, []) => {
+ projected.elements_chain = self.elements_chain.clone();
+ }
+ (GlobalRoot::Properties, [key]) => {
+ if let Some(value) = self.properties.get(key) {
+ projected.properties.insert(key.clone(), value.clone());
+ }
+ }
+ (GlobalRoot::Person, [scope, key]) if scope == "properties" => {
+ if let Some(value) = self.person_properties.get(key) {
+ projected
+ .person_properties
+ .insert(key.clone(), value.clone());
+ }
+ }
+ other => panic!(
+ "the generator produced a read this harness cannot project: {other:?}. \
+ Extend `projected` before extending the generator."
+ ),
+ }
+ }
+ projected.to_stream_event()
+ }
+}
+
+fn to_json_object(entries: &BTreeMap<String, String>) -> String {
+ Value::Object(
+ entries
+ .iter()
+ .map(|(key, value)| (key.clone(), Value::String(value.clone())))
+ .collect(),
+ )
+ .to_string()
+}
+
+/// [`EvalOutcome`] flattened to something comparable, keeping enough detail that two different
+/// failures are not read as agreement.
+fn verdict(outcome: EvalOutcome) -> String {
+ match outcome {
+ EvalOutcome::Matched(matched) => format!("matched:{matched}"),
+ EvalOutcome::UnknownFunction(name) => format!("unknown_function:{name}"),
+ EvalOutcome::VmError(error) => format!("vm_error:{error:?}"),
+ }
+}
+
+fn evaluate(bytecode: &[Value], event: &CohortStreamEvent) -> String {
+ let globals = build_behavioral_globals(event).expect("generated payloads are valid JSON");
+ verdict(evaluate_detailed(bytecode, globals))
+}
+
+// Small alphabets, so matches and non-matches both occur often. A generator over free-form strings
+// would make almost every comparison false and stop exercising the matching path.
+const VALUES: [&str; 5] = ["alpha", "beta", "gamma", "10", "2"];
+const EVENT_NAMES: [&str; 3] = ["purchase", "$pageview", "signup"];
+const PROPERTY_KEYS: [&str; 3] = ["plan", "country", "tier"];
+const PERSON_KEYS: [&str; 2] = ["email", "role"];
+const PATTERNS: [&str; 4] = ["%alpha%", "alpha", "a.*", "^beta$"];
+
+fn field_strategy() -> impl Strategy<Value = Field> {
+ prop_oneof![
+ Just(Field::Event),
+ Just(Field::DistinctId),
+ Just(Field::Timestamp),
+ Just(Field::ElementsChain),
+ prop::sample::select(&PROPERTY_KEYS[..]).prop_map(|key| Field::Property(key.to_owned())),
+ prop::sample::select(&PERSON_KEYS[..])
+ .prop_map(|key| Field::PersonProperty(key.to_owned())),
+ ]
+}
+
+fn ordering_op_strategy() -> impl Strategy<Value = CmpOp> {
+ prop_oneof![
+ Just(CmpOp::Gt),
+ Just(CmpOp::GtEq),
+ Just(CmpOp::Lt),
+ Just(CmpOp::LtEq),
+ ]
+}
+
+fn leaf_strategy() -> impl Strategy<Value = Expr> {
+ prop_oneof![
+ (
+ field_strategy(),
+ prop_oneof![
+ Just(CmpOp::Eq),
+ Just(CmpOp::NotEq),
+ Just(CmpOp::Gt),
+ Just(CmpOp::GtEq),
+ Just(CmpOp::Lt),
+ Just(CmpOp::LtEq),
+ ],
+ prop::sample::select(&VALUES[..]),
+ )
+ .prop_map(|(field, op, literal)| Expr::Compare {
+ field,
+ op,
+ literal: literal.to_owned(),
+ }),
+ (
+ field_strategy(),
+ ordering_op_strategy(),
+ prop::sample::select(&VALUES[..]),
+ )
+ .prop_map(|(field, op, literal)| Expr::NullSafeCompare {
+ field,
+ op,
+ literal: literal.to_owned(),
+ }),
+ (field_strategy(), prop::sample::select(&PATTERNS[..])).prop_map(|(field, pattern)| {
+ Expr::IfNullRegex {
+ field,
+ pattern: pattern.to_owned(),
+ }
+ }),
+ (
+ field_strategy(),
+ prop_oneof![Just(CmpOp::Like), Just(CmpOp::ILike), Just(CmpOp::Regex)],
+ prop::sample::select(&PATTERNS[..]),
+ )
+ .prop_map(|(field, op, literal)| Expr::Compare {
+ field,
+ op,
+ literal: literal.to_owned(),
+ }),
+ (
+ field_strategy(),
+ prop::collection::vec(prop::sample::select(&VALUES[..]), 1..4),
+ )
+ .prop_map(|(field, options)| Expr::InTuple {
+ field,
+ options: options.into_iter().map(str::to_owned).collect(),
+ }),
+ ]
+}
+
+fn expr_strategy() -> impl Strategy<Value = Expr> {
+ leaf_strategy().prop_recursive(3, 12, 3, |inner| {
+ prop_oneof![
+ prop::collection::vec(inner.clone(), 1..4).prop_map(Expr::All),
+ prop::collection::vec(inner, 1..4).prop_map(Expr::Any),
+ ]
+ })
+}
+
+fn event_strategy() -> impl Strategy<Value = TestEvent> {
+ (
+ prop::sample::select(&EVENT_NAMES[..]),
+ prop::sample::select(&VALUES[..]),
+ // A value or nothing per key. An absent key is what makes `isNull` true, so without these
+ // the null-safe comparison would only ever run its else arm and the guard the compiler
+ // wraps every ordering comparison in would go untested in one direction.
+ prop::collection::vec(
+ prop::option::of(prop::sample::select(&VALUES[..])),
+ PROPERTY_KEYS.len(),
+ ),
+ prop::collection::vec(
+ prop::option::of(prop::sample::select(&VALUES[..])),
+ PERSON_KEYS.len(),
+ ),
+ prop::sample::select(&VALUES[..]),
+ // Half the events leave the elements-chain column empty, which is what makes the globals
+ // fall back to `properties.$elements_chain`. Without those cases the fallback the analysis
+ // claims would never be exercised, and dropping the claim would go unnoticed.
+ any::<bool>(),
+ )
+ .prop_map(
+ |(event, distinct_id, property_values, person_values, chain, chain_in_column)| {
+ let mut properties: BTreeMap<String, String> = PROPERTY_KEYS
+ .iter()
+ .zip(property_values)
+ .filter_map(|(key, value)| Some(((*key).to_owned(), value?.to_owned())))
+ .collect();
+ // Keys no condition reads. A projection that dropped a claimed key fails; one that
+ // kept these extra keys does not, which is the asymmetry this test wants.
+ for noise in NOISE_KEYS {
+ properties.insert(noise.to_owned(), "noise".to_owned());
+ }
+ let rendered_chain = format!("a:href=\"/{chain}\"");
+ let elements_chain = if chain_in_column {
+ rendered_chain
+ } else {
+ properties.insert(ELEMENTS_CHAIN_PROPERTY.to_owned(), rendered_chain);
+ String::new()
+ };
+ TestEvent {
+ event: event.to_owned(),
+ distinct_id: distinct_id.to_owned(),
+ timestamp: "2026-05-26 12:34:56.789000".to_owned(),
+ elements_chain,
+ properties,
+ person_properties: PERSON_KEYS
+ .iter()
+ .zip(person_values)
+ .filter_map(|(key, value)| Some(((*key).to_owned(), value?.to_owned())))
+ .collect(),
+ }
+ },
+ )
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig::with_cases(512))]
+
+ /// The gate. For any generated condition the analysis narrows, evaluating it against only the
+ /// claimed globals must reach the same verdict as evaluating it against the whole event.
+ #[test]
+ fn a_claimed_read_set_is_enough_to_decide_the_condition(
+ expr in expr_strategy(),
+ event in event_strategy(),
+ ) {
+ let bytecode = program(&expr);
+ let Projection::Reads(paths) = analyze_condition(&bytecode).projection else {
+ // Every shape this generator emits is projectable, so a fallback here means the
+ // analysis lost precision on ordinary cohort bytecode rather than that the case is
+ // uninteresting.
+ prop_assert!(false, "{expr:?} was not narrowed");
+ return Ok(());
+ };
+ let full = evaluate(&bytecode, &event.to_stream_event());
+ let projected = evaluate(&bytecode, &event.projected(&paths));
+ prop_assert_eq!(
+ &full, &projected,
+ "{:?} read {:?} but disagreed once projected",
+ expr,
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>()
+ );
+ }
+
+ /// The same gate for `BETWEEN`, whose IIFE is the only generated shape that uses local slots.
+ /// A frame-base or slot-indexing mistake would either lose a read or claim one the program
+ /// never makes, and both show up as a disagreement here.
+ #[test]
+ fn a_between_iife_decides_from_its_claimed_read_set(
+ between in between_strategy(),
+ event in event_strategy(),
+ ) {
+ let bytecode = loaded(emit_between(&between));
+ let Projection::Reads(paths) = analyze_condition(&bytecode).projection else {
+ prop_assert!(false, "{between:?} was not narrowed");
+ return Ok(());
+ };
+ let full = evaluate(&bytecode, &event.to_stream_event());
+ let projected = evaluate(&bytecode, &event.projected(&paths));
+ prop_assert_eq!(
+ &full, &projected,
+ "{:?} read {:?} but disagreed once projected",
+ between,
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>()
+ );
+ }
+
+ /// Arbitrary token vectors, to cover the fail-closed contract as a class rather than one
+ /// instance at a time. The generated programs are almost all nonsense, which is the point: the
+ /// analysis is documented as total, and a catalog row is not a trusted input.
+ #[test]
+ fn analyzing_arbitrary_tokens_never_panics(tokens in token_vector_strategy()) {
+ let mut bytecode = vec![json!("_H"), json!(1)];
+ bytecode.extend(tokens);
+ analyze_condition(&bytecode);
+ }
+}
+
+/// Small integers around the opcode range, a few strings, and the hostile immediates: the values a
+/// corrupt or malicious catalog row could actually carry.
+fn token_strategy() -> impl Strategy<Value = Value> {
+ prop_oneof![
+ (0i64..60).prop_map(|number| json!(number)),
+ prop_oneof![
+ Just(json!(-1)),
+ Just(json!(i64::MIN)),
+ Just(json!(u64::MAX)),
+ Just(json!(4_000_000_000u64)),
+ ],
+ prop::sample::select(&["properties", "person", "event", "plan", "", "isNull"][..])
+ .prop_map(|text| json!(text)),
+ Just(json!(null)),
+ Just(json!(true)),
+ ]
+}
+
+/// Deliberately wide. A short cap only catches per-instruction mistakes, and the analysis's costs
+/// are per program: a pass that retained state per instruction was quadratic and allocated
+/// gigabytes on a few hundred tokens, which no 12-token case can reach.
+fn token_vector_strategy() -> impl Strategy<Value = Vec<Value>> {
+ prop::collection::vec(token_strategy(), 0..600)
+}
+
+fn between_strategy() -> impl Strategy<Value = Between> {
+ (field_strategy(), 0i64..12, 0i64..12).prop_map(|(field, low, high)| Between {
+ field,
+ low,
+ high,
+ })
+}
+
+/// The harness has to be able to fail. Dropping one claimed key from the projection must make some
+/// generated condition disagree; if it did not, the equivalence property above would be vacuous.
+#[test]
+fn dropping_a_claimed_key_makes_the_two_evaluations_disagree() {
+ let expr = Expr::Compare {
+ field: Field::Property("plan".to_owned()),
+ op: CmpOp::Eq,
+ literal: "alpha".to_owned(),
+ };
+ let bytecode = program(&expr);
+ let Projection::Reads(paths) = analyze_condition(&bytecode).projection else {
+ panic!("a single property comparison must narrow");
+ };
+ assert_eq!(
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>(),
+ ["properties.plan"]
+ );
+
+ let event = TestEvent {
+ event: "purchase".to_owned(),
+ distinct_id: "d-1".to_owned(),
+ timestamp: "2026-05-26 12:34:56.789000".to_owned(),
+ elements_chain: String::new(),
+ properties: BTreeMap::from([("plan".to_owned(), "alpha".to_owned())]),
+ person_properties: BTreeMap::new(),
+ };
+ assert_eq!(
+ evaluate(&bytecode, &event.to_stream_event()),
+ "matched:true"
+ );
+ assert_eq!(
+ evaluate(&bytecode, &event.projected(&paths)),
+ "matched:true"
+ );
+ assert_eq!(
+ evaluate(&bytecode, &event.projected(&BTreeSet::new())),
+ "matched:false",
+ "projecting nothing still matched, so the comparison never depended on the key"
+ );
+}
+
+/// The emitter must produce what the compiler produces. This pins the one program whose real
+/// compiled form is known from the catalog loader's own fixtures, so a change to the emitter that
+/// drifted from the compiler would be caught here rather than silently weakening every case above.
+#[test]
+fn the_emitter_matches_the_compilers_output_for_an_event_equality() {
+ let expr = Expr::Compare {
+ field: Field::Event,
+ op: CmpOp::Eq,
+ literal: "purchase".to_owned(),
+ };
+ assert_eq!(
+ program(&expr),
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!("purchase"),
+ json!(32),
+ json!("event"),
+ json!(1),
+ json!(1),
+ json!(11),
+ json!(38),
+ ]
+ );
+}
+
+/// The null-safe emitter must produce what the compiler produces.
+///
+/// Pinned against `isnull_numeric_gte_match.json`, a fixture holding real compiled cohort bytecode,
+/// with only the property key and the literal changed. The `JUMP_IF_FALSE 3` and the `JUMP` over an
+/// else arm exactly as long as the comparison are the two numbers that make the shape a control
+/// flow graph rather than a straight line — an emitter that drifted on either would leave every
+/// generated case testing something the compiler never emits.
+#[test]
+fn the_emitter_matches_the_compilers_null_safe_comparison() {
+ let expr = Expr::NullSafeCompare {
+ field: Field::Property("$screen_height".to_owned()),
+ op: CmpOp::GtEq,
+ literal: "500".to_owned(),
+ };
+ assert_eq!(
+ emit(&expr),
+ vec![
+ json!(32),
+ json!("$screen_height"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(2),
+ json!("isNull"),
+ json!(1),
+ json!(32),
+ json!("500"),
+ json!(2),
+ json!("isNull"),
+ json!(1),
+ json!(4),
+ json!(2),
+ json!(40),
+ json!(3),
+ json!(30),
+ json!(39),
+ json!(9),
+ json!(32),
+ json!("500"),
+ json!(32),
+ json!("$screen_height"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(14),
+ ]
+ );
+}
+
+/// The `ifNull` regex shape, as `property.py` builds it: `ifNull(match(toString(x), p), 0)`. The
+/// jump skips both the `POP` and the two-token null arm, which is what leaves the two paths at the
+/// same stack depth where they meet.
+#[test]
+fn the_emitter_matches_the_compilers_ifnull_regex() {
+ let expr = Expr::IfNullRegex {
+ field: Field::Property("plan".to_owned()),
+ pattern: "a.*".to_owned(),
+ };
+ assert_eq!(
+ emit(&expr),
+ vec![
+ json!(32),
+ json!("plan"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(2),
+ json!("toString"),
+ json!(1),
+ json!(32),
+ json!("a.*"),
+ json!(2),
+ json!("match"),
+ json!(2),
+ json!(47),
+ json!(3),
+ json!(35),
+ json!(33),
+ json!(0),
+ ]
+ );
+}
+
+/// A nested path must be pushed leaf first, so `GET_GLOBAL` pops `properties` before `plan`. The
+/// reversed reading would record `plan.properties` and project a column that does not exist.
+#[test]
+fn a_nested_path_is_emitted_leaf_first_and_read_root_first() {
+ let expr = Expr::Compare {
+ field: Field::Property("plan".to_owned()),
+ op: CmpOp::Eq,
+ literal: "alpha".to_owned(),
+ };
+ let bytecode = program(&expr);
+ assert_eq!(
+ &bytecode[4..10],
+ &[
+ json!(32),
+ json!("plan"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ ]
+ );
+ let Projection::Reads(paths) = analyze_condition(&bytecode).projection else {
+ panic!("a single property comparison must narrow");
+ };
+ assert_eq!(
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>(),
+ ["properties.plan"]
+ );
+}
diff --git a/rust/cohort-core/tests/analysis_parity_corpus.rs b/rust/cohort-core/tests/analysis_parity_corpus.rs
new file mode 100644
index 000000000000..d1d379b99f72
--- /dev/null
+++ b/rust/cohort-core/tests/analysis_parity_corpus.rs
@@ -0,0 +1,233 @@
+//! Runs the cohort parity fixtures through the static analysis.
+//!
+//! These are real compiled cohort bytecode: each fixture carries the program, the globals it runs
+//! against, and the verdict the Python oracle reached. That makes them the only corpus here that
+//! can answer the question the analysis exists to answer — whether the read set it claims is enough
+//! to decide a condition production actually compiles.
+//!
+//! The check is the same equivalence the proptest gate asserts, run against compiled rather than
+//! synthesized programs: prune the globals down to exactly the claimed paths, evaluate again, and
+//! require the same verdict the oracle recorded. A read set that were ever short would decide the
+//! wrong way here.
+
+use std::collections::BTreeSet;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use cohort_core::hogvm::analysis::{analyze_condition, Projection, ReadPath};
+use cohort_core::{evaluate_detailed, EvalOutcome};
+use serde_json::{Map, Value};
+
+/// The catalog loader appends a `RETURN` to every stored program, and the parity runner does the
+/// same, so the analysis has to see the bytecode in that form and not the raw fixture.
+const OP_RETURN: i64 = 38;
+
+/// The fixture shapes whose bytecode the compiler lowers through jumps: `null_safe_comparisons`
+/// rewrites `>=` into an `if`, and a date comparison goes the same way. They are named here because
+/// they are the reason the interpreter follows branches at all — an analysis that refused them
+/// would report almost every real date and numeric condition as unreadable, and the census built on
+/// it would answer the wrong question.
+const BRANCH_LOWERED_FIXTURES: [&str; 5] = [
+ "isnull_numeric_gte_below",
+ "isnull_numeric_gte_match",
+ "isnull_numeric_gte_null",
+ "to_datetime_eq_bare_field",
+ "to_datetime_ordering_lt",
+];
+
+struct Fixture {
+ name: String,
+ bytecode: Vec<Value>,
+ globals: Value,
+ expected: bool,
+}
+
+fn fixtures() -> Vec<Fixture> {
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../cohort-stream-processor/tests/fixtures/hogvm_parity");
+ let mut paths = fs::read_dir(&dir)
+ .unwrap_or_else(|error| panic!("the parity fixtures are not readable at {dir:?}: {error}"))
+ .map(|entry| entry.expect("a directory entry is readable").path())
+ .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
+ .collect::<Vec<PathBuf>>();
+ paths.sort();
+
+ paths
+ .iter()
+ .map(|path| {
+ let text = fs::read_to_string(path).expect("a fixture is readable");
+ let fixture: Value = serde_json::from_str(&text)
+ .unwrap_or_else(|error| panic!("fixture {path:?} is not JSON: {error}"));
+ let mut bytecode = fixture["bytecode"]
+ .as_array()
+ .unwrap_or_else(|| panic!("fixture {path:?} has no bytecode array"))
+ .clone();
+ bytecode.push(Value::from(OP_RETURN));
+ Fixture {
+ name: fixture["name"].as_str().unwrap_or("<unnamed>").to_owned(),
+ bytecode,
+ globals: fixture["globals"].clone(),
+ // `unwrap_or(false)` mirrors the parity runner's coercion.
+ expected: fixture["expected_result"].as_bool().unwrap_or(false),
+ }
+ })
+ .collect()
+}
+
+/// The globals a scan built from `paths` would produce: every value the analysis did not claim is
+/// absent, exactly as a narrower `SELECT` would leave it.
+///
+/// The objects along a claimed path are created whether or not the leaf is there. That is what a
+/// narrower query actually returns — the `properties` column still arrives, holding fewer keys —
+/// and the distinction is load-bearing, because the VM reads a missing key inside an object as null
+/// but raises on a missing object.
+fn project_globals(globals: &Value, paths: &BTreeSet<ReadPath>) -> Value {
+ let mut projected = Map::new();
+ for path in paths {
+ let mut keys = vec![path.root.as_str().to_owned()];
+ keys.extend(path.segments.iter().cloned());
+ graft(&mut projected, &keys, lookup(globals, &keys));
+ }
+ Value::Object(projected)
+}
+
+fn lookup<'a>(globals: &'a Value, keys: &[String]) -> Option<&'a Value> {
+ keys.iter()
+ .try_fold(globals, |value, key| value.as_object()?.get(key))
+}
+
+fn graft(into: &mut Map<String, Value>, keys: &[String], value: Option<&Value>) {
+ let Some((key, rest)) = keys.split_first() else {
+ return;
+ };
+ if rest.is_empty() {
+ if let Some(value) = value {
+ into.insert(key.clone(), value.clone());
+ }
+ return;
+ }
+ let child = into
+ .entry(key.clone())
+ .or_insert_with(|| Value::Object(Map::new()));
+ // A path claimed both bare and nested would collide here. The analysis never emits a bare
+ // object root as a read, so the nested form is the only one that reaches this.
+ if let Some(object) = child.as_object_mut() {
+ graft(object, rest, value);
+ }
+}
+
+/// Every path the projection kept has to lie on a claimed one: under it, where a claim names a
+/// subtree, or on the way to it, for the objects [`graft`] creates along a claimed path.
+///
+/// Without this the corpus cannot fail on a leak. Each fixture's property bag holds at most the one
+/// key its condition reads, so a `project_globals` that returned whole objects instead of the
+/// claimed keys would decide every fixture the same way and pass — leaving the test asserting that
+/// the full globals decide the condition, which is trivially true. The generated corpus is
+/// projected key by key and so cannot leak by construction; this is the same guarantee for the
+/// programs that came out of the real compiler.
+fn assert_nothing_outside_the_claimed_paths(
+ projected: &Value,
+ paths: &BTreeSet<ReadPath>,
+ name: &str,
+) {
+ let claimed: Vec<Vec<String>> = paths
+ .iter()
+ .map(|path| {
+ let mut keys = vec![path.root.as_str().to_owned()];
+ keys.extend(path.segments.iter().cloned());
+ keys
+ })
+ .collect();
+ assert_kept_path_is_claimed(projected, &mut Vec::new(), &claimed, name);
+}
+
+fn assert_kept_path_is_claimed(
+ value: &Value,
+ at: &mut Vec<String>,
+ claimed: &[Vec<String>],
+ name: &str,
+) {
+ if let Value::Object(fields) = value {
+ if !fields.is_empty() {
+ for (key, child) in fields {
+ at.push(key.clone());
+ assert_kept_path_is_claimed(child, at, claimed, name);
+ at.pop();
+ }
+ return;
+ }
+ }
+ // An empty path is the whole projection being empty, which cannot carry anything unclaimed.
+ assert!(
+ at.is_empty()
+ || claimed
+ .iter()
+ .any(|path| path.starts_with(at) || at.starts_with(path)),
+ "fixture `{name}` kept {at:?}, which no claimed path covers"
+ );
+}
+
+fn matched(bytecode: &[Value], globals: Value, name: &str) -> bool {
+ match evaluate_detailed(bytecode, globals) {
+ EvalOutcome::Matched(matched) => matched,
+ other => panic!("fixture `{name}` did not evaluate cleanly: {other:?}"),
+ }
+}
+
+/// Every fixture analyzes, and where the analysis claims a read set, that set alone decides the
+/// condition the same way the oracle did — with the projection holding nothing the analysis did not
+/// claim, so the equivalence is about the claimed set rather than about the whole event.
+#[test]
+fn every_parity_fixture_decides_the_same_way_from_its_claimed_reads() {
+ let fixtures = fixtures();
+ assert!(
+ fixtures.len() >= 10,
+ "only {} parity fixtures; this test would stop covering the compiled shapes",
+ fixtures.len()
+ );
+ for fixture in &fixtures {
+ let full = matched(&fixture.bytecode, fixture.globals.clone(), &fixture.name);
+ assert_eq!(
+ full, fixture.expected,
+ "fixture `{}` disagrees with its own oracle before any projection",
+ fixture.name
+ );
+ let Projection::Reads(paths) = analyze_condition(&fixture.bytecode).projection else {
+ continue;
+ };
+ let projected_globals = project_globals(&fixture.globals, &paths);
+ assert_nothing_outside_the_claimed_paths(&projected_globals, &paths, &fixture.name);
+ let projected = matched(&fixture.bytecode, projected_globals, &fixture.name);
+ assert_eq!(
+ projected,
+ fixture.expected,
+ "fixture `{}` claimed {:?} but decided differently once projected onto it",
+ fixture.name,
+ paths.iter().map(ReadPath::render).collect::<Vec<_>>()
+ );
+ }
+}
+
+/// The conditions the compiler lowers through jumps must narrow to a read set.
+///
+/// This is the regression that matters most: while the interpreter refused branches, every one of
+/// these reported full columns, so a census over a real catalog would have counted the commonest
+/// property-filtered conditions as unreadable and understated what a projection can do.
+#[test]
+fn the_branch_lowered_fixtures_narrow_to_a_read_set() {
+ let fixtures = fixtures();
+ for name in BRANCH_LOWERED_FIXTURES {
+ let fixture = fixtures
+ .iter()
+ .find(|fixture| fixture.name == name)
+ .unwrap_or_else(|| panic!("the `{name}` parity fixture is gone"));
+ let projection = analyze_condition(&fixture.bytecode).projection;
+ let Projection::Reads(paths) = projection else {
+ panic!("`{name}` compiles through a jump and did not narrow: {projection:?}");
+ };
+ assert!(
+ !paths.is_empty(),
+ "`{name}` narrowed to an empty read set, which cannot be right for a property filter"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rs
index b05f9f7bd373..aad064c95761 100644
--- a/rust/cohort-seeder/src/app/prepare.rs
+++ b/rust/cohort-seeder/src/app/prepare.rs
@@ -11,21 +11,21 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use cohort_core::bucket_tz::window_start_for_now;
-use cohort_core::filters::CohortId;
+use cohort_core::filters::{CohortId, TeamId};
use common_types::cohort::TeamAllowlist;
use metrics::{counter, gauge};
use sqlx::PgPool;
-use tracing::warn;
+use tracing::{debug, info, warn};
use crate::domain::{
- plan_days, Lookback, PersonRunValidation, PinnedPersonRun, PinnedRun, PinnedWarning, PlanCaps,
- RunId,
+ plan_days, ConditionAnalyses, ConditionClass, Lookback, PersonRunValidation, PinnedPersonRun,
+ PinnedRun, PinnedWarning, PlanCaps, RunId,
};
use crate::observability::metrics::{
- BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_DROPPED,
- LOOKBACK_TRUNCATED, RUNS_DISCOVERED, RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD,
- RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS, RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES,
- TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
+ BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_CLASSIFIED,
+ CONDITIONS_DROPPED, CONDITIONS_UNANALYZABLE, LOOKBACK_TRUNCATED, RUNS_DISCOVERED,
+ RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS,
+ RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
};
use crate::store::chunks::{PgChunkStore, PlanOutcome};
use crate::store::completion::{mark_chunks_planned, read_planning_stamp, PlanningStampOutcome};
@@ -87,7 +87,7 @@ pub(super) async fn refresh_runs(
for run in discovered {
seen_runs.insert(run.run_id);
let kind = run.kind;
- match prepare_run(pool, store, plan_caps, reported_runs, run).await {
+ match prepare_run(pool, store, allowlist, plan_caps, reported_runs, run).await {
PrepareOutcome::Eligible(prepared) => {
let run_id = match &prepared {
PreparedRun::Behavioral(run) => run.run_id,
@@ -130,6 +130,7 @@ pub(super) async fn refresh_runs(
async fn prepare_run(
pool: &PgPool,
store: &PgChunkStore,
+ allowlist: &TeamAllowlist,
plan_caps: PlanCaps,
reported_runs: &mut HashSet<RunId>,
run: DiscoveredRun,
@@ -146,7 +147,7 @@ async fn prepare_run(
};
match kind {
RunKind::Behavioral => {
- prepare_behavioral(pool, store, plan_caps, reported_runs, boundary).await
+ prepare_behavioral(pool, store, allowlist, plan_caps, reported_runs, boundary).await
}
RunKind::PersonProperty => prepare_person(pool, store, reported_runs, boundary).await,
}
@@ -184,6 +185,7 @@ async fn resolve_boundary(pool: &PgPool, run: DiscoveredRun) -> Option<Resolved>
async fn prepare_behavioral(
pool: &PgPool,
store: &PgChunkStore,
+ allowlist: &TeamAllowlist,
plan_caps: PlanCaps,
reported_runs: &mut HashSet<RunId>,
boundary: SeedableRun,
@@ -199,6 +201,7 @@ async fn prepare_behavioral(
let lookback_truncated = lookback_was_truncated(&validated.run, plan_caps);
if reported_runs.insert(run_id) {
record_pinned_warnings(&validated.warnings);
+ record_condition_census(allowlist, run_id, &validated.run);
if lookback_truncated {
counter!(LOOKBACK_TRUNCATED).increment(1);
}
@@ -397,6 +400,100 @@ async fn persist_run_warning(pool: &PgPool, run_id: RunId, note: RunWarningNote)
}
}
+/// Publish what a static read of the run's condition bytecode found.
+///
+/// The analysis is built here rather than during validation, so it runs exactly once per run per
+/// stretch: this is already behind the `reported_runs` gate, where validation is not. Validation
+/// runs every poll tick, and the decode is the one place the seeder interprets an untrusted catalog
+/// value.
+///
+/// This runs inline on the task that owes the liveness heartbeat, so its cost has to be bounded by
+/// the run rather than by the condition: nothing caps behavioral conditions on a run, and the
+/// `reported_runs` gate does not help after a restart, when every active run is new again.
+/// `ConditionAnalyses::build` gives the run's conditions one shared budget for that. The gate is
+/// still what keeps the *ordinary* cost small — the same tick already parses every discovered run's
+/// whole pinned payload during validation, which is more work than analyzing that payload once.
+///
+/// Nothing consumes the analysis yet. The point is to learn the shape of real catalogs before any
+/// scan is built on one: which event names a projection could narrow, and what blocks the rest.
+fn record_condition_census(allowlist: &TeamAllowlist, run_id: RunId, run: &PinnedRun) {
+ let census = ConditionAnalyses::build(&run.conditions, &run.filters).census(&run.conditions);
+ if census.total() == 0 {
+ return;
+ }
+ let team = team_label(allowlist, run.team_id);
+ for class in ConditionClass::ALL {
+ let count = census.count(class);
+ if count > 0 {
+ counter!(
+ CONDITIONS_CLASSIFIED,
+ "class" => class.as_str(),
+ "team_id" => team.clone(),
+ )
+ .increment(count);
+ }
+ }
+ for (label, count) in &census.unanalyzable_reasons {
+ counter!(
+ CONDITIONS_UNANALYZABLE,
+ "reason" => label.reason,
+ "op" => label.op.clone().unwrap_or_else(|| Arc::from("none")),
+ "team_id" => team.clone(),
+ )
+ .increment(*count);
+ }
+ info!(
+ ?run_id,
+ team_id = run.team_id.0,
+ conditions = census.total(),
+ event_only = census.count(ConditionClass::EventOnly),
+ projectable = census.count(ConditionClass::Projectable),
+ full_columns = census.count(ConditionClass::FullColumns),
+ unanalyzable = census.count(ConditionClass::Unanalyzable),
+ property_projectable_fraction = census.property_projectable_fraction(),
+ eligible_events = census.projection_eligible_event_names().len(),
+ blocked_events = %census.render_blocked_events(),
+ "condition bytecode analysis census",
+ );
+ // The read sets and the uncapped blocked list carry customer-defined event names and property
+ // keys, and run to several kilobytes on a large catalog. Values are never included, but the
+ // keys alone are enough to keep this off the default level. Named apart from the line above's
+ // `blocked_events` because that one is truncated and this one is not, and a query that mixed
+ // them would read a partial list as a whole one.
+ debug!(
+ ?run_id,
+ reads = %census.render_reads(),
+ all_blocked_events = %census.render_all_blocked_events(),
+ "condition bytecode analysis reads and blockers",
+ );
+}
+
+/// How many teams the census names individually before it stops naming any.
+///
+/// Sized well above the shadow rollout's team count, so the collapse is a ceiling rather than a
+/// routine truncation.
+const MAX_LABELLED_TEAMS: usize = 32;
+
+/// The label every team shares once the census stops naming them.
+const UNLABELLED_TEAM: &str = "other";
+
+/// The team a census belongs to, as a metric label.
+///
+/// A team gets its own series only while `REALTIME_COHORT_TEAM_ALLOWLIST` names few enough of them.
+/// The allowlist does not bound this on its own: it accepts `all` (which a set-but-empty variable
+/// also parses to) and ranges of up to 100,000 ids, and the recorder never evicts a series, so a
+/// wide rollout would retain one per team that ever seeded. The label is here because the
+/// deliverable is one team's number, which a blended counter cannot give; the per-run log line
+/// carries the exact team either way, so collapsing costs the dashboard, not the answer.
+fn team_label(allowlist: &TeamAllowlist, team_id: TeamId) -> Arc<str> {
+ match allowlist {
+ TeamAllowlist::Only(ids) if ids.len() <= MAX_LABELLED_TEAMS => {
+ Arc::from(team_id.0.to_string().as_str())
+ }
+ TeamAllowlist::Only(_) | TeamAllowlist::All => Arc::from(UNLABELLED_TEAM),
+ }
+}
+
fn record_pinned_warnings(warnings: &[PinnedWarning]) {
for warning in warnings {
match warning {
@@ -466,3 +563,34 @@ fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDis
| RunError::NotActive(_) => RunErrorDisposition::Retry,
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashSet;
+
+ use super::*;
+
+ /// An allowlist that can grow with the customer base must not mint a metric series per team.
+ /// The recorder never evicts one, so a label that tracks team count leaks for the whole process
+ /// lifetime — and `all`, which a set-but-empty variable also parses to, is the configuration
+ /// the boundedness claim used to assume away.
+ #[test]
+ fn only_a_narrow_allowlist_names_teams_in_the_census_label() {
+ let narrow = TeamAllowlist::Only(HashSet::from([2, 7]));
+ assert_eq!(&*team_label(&narrow, TeamId(2)), "2");
+
+ let wide = TeamAllowlist::Only((0..=MAX_LABELLED_TEAMS as i32).collect());
+ assert_eq!(&*team_label(&wide, TeamId(2)), UNLABELLED_TEAM);
+ assert_eq!(
+ &*team_label(&TeamAllowlist::All, TeamId(2)),
+ UNLABELLED_TEAM
+ );
+ assert_eq!(
+ &*team_label(
+ &"".parse::<TeamAllowlist>().expect("blank parses"),
+ TeamId(2)
+ ),
+ UNLABELLED_TEAM
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/condition_analysis.rs b/rust/cohort-seeder/src/domain/condition_analysis.rs
new file mode 100644
index 000000000000..940d3990963b
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/condition_analysis.rs
@@ -0,0 +1,702 @@
+//! Domain layer: the static analysis of a run's pinned conditions, and the census over it.
+//! Depends on `condition`, `ids`, and `cohort-core`.
+//!
+//! Nothing in the scan path consumes the analysis yet: it is published as counters and one log line
+//! per run, so the shape of real catalogs is known before anything is built on it.
+//!
+//! The census is shaped around the question a later projection pass has to answer, which is
+//! per event name rather than per condition. A scan selects columns for a whole event, so one
+//! condition on `$pageview` that cannot be narrowed forces full columns for every `$pageview` row,
+//! however many of its siblings are narrow. Counting conditions alone would report that event as
+//! mostly projectable and overstate what a projection can do — on exactly the fat events where it
+//! matters.
+//!
+//! Being a pure function of the pinned payload is what makes it safe to run per run rather than per
+//! chunk: a re-validated run classifies identically, so a chunk retried on another replica cannot
+//! disagree with the first attempt.
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::sync::Arc;
+
+use cohort_core::filters::TeamFilters;
+use cohort_core::hogvm::analysis::{
+ analyze_condition_within, AnalysisBudget, ConditionAnalysis, EvaluationClass,
+ FullColumnsReason, Projection, ReadPath,
+};
+
+use super::condition::PinnedCondition;
+use super::ids::ConditionHash;
+
+/// What one condition turned out to need. Ordered so a census renders the same way every time.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum ConditionClass {
+ /// Nothing but an event-name equality, which a scan's event filter already decides.
+ EventOnly,
+ /// Reads a named, narrow set of globals.
+ Projectable,
+ /// Understood, but reads a whole object, so every column is needed.
+ FullColumns,
+ /// Not understood, so it falls back to every column.
+ Unanalyzable,
+}
+
+impl ConditionClass {
+ pub const ALL: [Self; 4] = [
+ Self::EventOnly,
+ Self::Projectable,
+ Self::FullColumns,
+ Self::Unanalyzable,
+ ];
+
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::EventOnly => "event_only",
+ Self::Projectable => "projectable",
+ Self::FullColumns => "full_columns",
+ Self::Unanalyzable => "unanalyzable",
+ }
+ }
+
+ /// Whether this class forces a scan to select every column for its event name.
+ const fn is_unprojectable(self) -> bool {
+ matches!(self, Self::FullColumns | Self::Unanalyzable)
+ }
+
+ fn of(analysis: &ConditionAnalysis) -> Self {
+ match (&analysis.evaluation, &analysis.projection) {
+ // An event-name equality needs no per-row evaluation, so its projection is irrelevant —
+ // except when the projection itself failed, which means the two passes disagree about
+ // what the program is. Classifying by the projection there fails wide rather than
+ // narrow, which is the direction a wrong answer has to fall.
+ (EvaluationClass::EventOnly { .. }, Projection::Reads(_)) => Self::EventOnly,
+ // Exhaustive rather than defaulted, like every other reason mapping in this chain. A
+ // new `FullColumnsReason` landing in `FullColumns` by default would be reported as an
+ // understood outcome: only `Unanalyzable` reaches the reason counter, so the census
+ // would describe a brand new failure mode as expected.
+ (EvaluationClass::EventOnly { .. }, Projection::FullColumns(reason))
+ | (EvaluationClass::General, Projection::FullColumns(reason)) => match reason {
+ FullColumnsReason::Unanalyzable(_) => Self::Unanalyzable,
+ FullColumnsReason::BarePropertiesRoot | FullColumnsReason::BarePersonRoot => {
+ Self::FullColumns
+ }
+ },
+ (EvaluationClass::General, Projection::Reads(_)) => Self::Projectable,
+ }
+ }
+}
+
+/// The label for a pinned condition whose hash the frozen catalog has no bytecode for. Not an
+/// analysis outcome: the condition never reached the analyzer.
+pub const MISSING_BYTECODE_REASON: &str = "missing_bytecode";
+
+/// How many blocked event names the per-run log line names before it starts counting instead.
+/// Sized to hold a large team's whole blocked set, so the cap is a ceiling rather than a routine
+/// truncation.
+const MAX_RENDERED_BLOCKED_EVENTS: usize = 50;
+
+/// How many worst-case conditions one run's census may cost, as one budget its conditions share.
+///
+/// The analyzer bounds each condition, which leaves `conditions × ceiling` for a run — and nothing
+/// caps behavioral conditions per run, so that product is unbounded. Sharing one budget bounds the
+/// run instead. Past it the remaining conditions report the budget and fall back to every column,
+/// which the census counts under its own reason rather than hiding.
+///
+/// A budget rather than a deadline because [`ConditionAnalyses::build`] has to stay a pure function
+/// of the pinned payload: two replicas re-validating one run must classify it identically, and a
+/// wall clock would not.
+const CENSUS_WORST_CASE_CONDITIONS: usize = 8;
+
+/// One analysis per unique pinned condition hash.
+///
+/// Person runs are deliberately absent. Their conditions read the small person-scope globals rather
+/// than the event globals this analysis models, so classifying them here would report against the
+/// wrong vocabulary.
+#[derive(Debug, Default)]
+pub struct ConditionAnalyses {
+ by_hash: HashMap<ConditionHash, ConditionAnalysis>,
+}
+
+impl ConditionAnalyses {
+ /// Analyze every unique hash among `conditions` whose bytecode the frozen catalog carries,
+ /// under one budget they share — see [`CENSUS_WORST_CASE_CONDITIONS`].
+ ///
+ /// `conditions` is walked in order, so the budget is spent the same way every time and the
+ /// result stays a pure function of the pinned payload.
+ pub fn build(conditions: &[PinnedCondition], filters: &TeamFilters) -> Self {
+ let mut budget = AnalysisBudget::for_conditions(CENSUS_WORST_CASE_CONDITIONS);
+ let mut by_hash = HashMap::new();
+ for condition in conditions {
+ if by_hash.contains_key(&condition.hash) {
+ continue;
+ }
+ let Some(bytecode) = filters
+ .by_condition_to_bytecode
+ .get(&condition.hash.as_bytes())
+ else {
+ continue;
+ };
+ by_hash.insert(
+ condition.hash,
+ analyze_condition_within(bytecode.as_slice(), &mut budget),
+ );
+ }
+ Self { by_hash }
+ }
+
+ /// Count the conditions by class, and account for each event name what a projection over it
+ /// would have to supply.
+ ///
+ /// Counted per unique hash and event name, not per pinned condition: the same condition shared
+ /// by several cohorts is one piece of work, and counting it twice would overstate the
+ /// projectable share.
+ ///
+ /// The event name is part of the key rather than the hash alone, because the two arrive as
+ /// independent fields of the Django payload. Deduplicating on the hash would skip a repeated
+ /// hash before it reached its second event name, and that event would then be accounted from
+ /// its other conditions alone — projection-eligible on paper while carrying a condition that
+ /// needs every column.
+ pub fn census(&self, conditions: &[PinnedCondition]) -> ConditionCensus {
+ let mut census = ConditionCensus::default();
+ let mut seen: BTreeSet<(ConditionHash, &str)> = BTreeSet::new();
+ for condition in conditions {
+ if !seen.insert((condition.hash, condition.event_name.as_str())) {
+ continue;
+ }
+ let event = census
+ .per_event
+ .entry(condition.event_name.clone())
+ .or_default();
+ let Some(analysis) = self.by_hash.get(&condition.hash) else {
+ // Unreachable today: `resolve_conditions` drops any hash the frozen catalog has no
+ // bytecode for, so every surviving condition has one. Kept because the alternative
+ // to a label here is a condition that silently leaves no trace in the census.
+ *census
+ .by_class
+ .entry(ConditionClass::Unanalyzable)
+ .or_default() += 1;
+ *census
+ .unanalyzable_reasons
+ .entry(UnanalyzableLabel::missing_bytecode())
+ .or_default() += 1;
+ event.unprojectable += 1;
+ event.blockers.insert(MISSING_BYTECODE_REASON.to_owned());
+ continue;
+ };
+ let class = ConditionClass::of(analysis);
+ *census.by_class.entry(class).or_default() += 1;
+ match class {
+ ConditionClass::EventOnly => event.event_only += 1,
+ ConditionClass::Projectable => event.projectable += 1,
+ _ => event.unprojectable += 1,
+ }
+ if let Projection::FullColumns(reason) = &analysis.projection {
+ let label = UnanalyzableLabel::of(reason);
+ if class.is_unprojectable() {
+ event.blockers.insert(label.render());
+ }
+ if class == ConditionClass::Unanalyzable {
+ *census.unanalyzable_reasons.entry(label).or_default() += 1;
+ }
+ }
+ if let Projection::Reads(paths) = &analysis.projection {
+ event.reads.extend(paths.iter().map(ReadPath::render));
+ }
+ }
+ census
+ }
+}
+
+/// A reason label pair: the coarse reason, plus the opcode when one is what stopped the analysis.
+///
+/// Both halves are closed vocabularies — the reason by construction, the opcode because
+/// `Operation` is a 57-variant enum — so the pair is safe as a metric dimension. The opcode is
+/// carried because "unsupported_op" alone cannot tell one fixable compiler template apart from a
+/// program nothing will ever narrow, which is the difference the census exists to report.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub struct UnanalyzableLabel {
+ pub reason: &'static str,
+ /// The opcode's variant name, from its `Debug` rendering. `Arc<str>` because the metric layer
+ /// clones a label value per emission and the repo's convention is a refcount bump rather than
+ /// an allocation.
+ pub op: Option<Arc<str>>,
+}
+
+impl UnanalyzableLabel {
+ fn of(reason: &FullColumnsReason) -> Self {
+ Self {
+ reason: reason.as_str(),
+ op: reason.op().map(|op| Arc::from(format!("{op:?}").as_str())),
+ }
+ }
+
+ fn missing_bytecode() -> Self {
+ Self {
+ reason: MISSING_BYTECODE_REASON,
+ op: None,
+ }
+ }
+
+ /// The label as one string, for the log line and the per-event blocker set.
+ pub fn render(&self) -> String {
+ match &self.op {
+ Some(op) => format!("{}:{op}", self.reason),
+ None => self.reason.to_owned(),
+ }
+ }
+}
+
+/// What the conditions on one event name would cost a projection over it.
+///
+/// The counts are per unique condition hash on that event name. `unprojectable` is the one that
+/// decides: a scan selects columns for the whole event, so one unprojectable condition forces full
+/// columns for every row of it.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct EventCensus {
+ pub event_only: u64,
+ pub projectable: u64,
+ pub unprojectable: u64,
+ /// The union of what the narrow conditions on this event name read, rendered dotted.
+ pub reads: BTreeSet<String>,
+ /// Why the unprojectable ones are, as rendered [`UnanalyzableLabel`]s.
+ pub blockers: BTreeSet<String>,
+}
+
+impl EventCensus {
+ /// Whether a projection over this event name is possible at all.
+ pub const fn is_projection_eligible(&self) -> bool {
+ self.unprojectable == 0
+ }
+}
+
+/// The per-run shape report. Every collection is ordered, so two runs over the same catalog log the
+/// same text and a census can be compared across replicas.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct ConditionCensus {
+ pub by_class: BTreeMap<ConditionClass, u64>,
+ pub unanalyzable_reasons: BTreeMap<UnanalyzableLabel, u64>,
+ /// One entry per event name any pinned condition references.
+ pub per_event: BTreeMap<String, EventCensus>,
+}
+
+impl ConditionCensus {
+ pub fn total(&self) -> u64 {
+ self.by_class.values().sum()
+ }
+
+ pub fn count(&self, class: ConditionClass) -> u64 {
+ self.by_class.get(&class).copied().unwrap_or(0)
+ }
+
+ /// The share of *property-filtered* conditions a projection could narrow.
+ ///
+ /// Event-only conditions are excluded from both halves rather than counted as wins. They are
+ /// the majority of conditions on a real catalog and a small minority of the rows scanned, so
+ /// including them produces a high number that says nothing about the work a projection would
+ /// save — which is the ranking error this census exists to avoid repeating. Zero when there is
+ /// nothing to classify, so an empty run reports no misleading fraction.
+ pub fn property_projectable_fraction(&self) -> f64 {
+ let projectable = self.count(ConditionClass::Projectable);
+ let denominator = projectable
+ + self.count(ConditionClass::FullColumns)
+ + self.count(ConditionClass::Unanalyzable);
+ if denominator == 0 {
+ return 0.0;
+ }
+ projectable as f64 / denominator as f64
+ }
+
+ /// The event names a projection could narrow, meaning every condition on them is narrow.
+ pub fn projection_eligible_event_names(&self) -> Vec<&str> {
+ self.per_event
+ .iter()
+ .filter(|(_, event)| event.is_projection_eligible())
+ .map(|(name, _)| name.as_str())
+ .collect()
+ }
+
+ /// The event names a projection could not narrow, each with why. This is the list to join
+ /// against per-event row volume: an event here costs full columns however many of its
+ /// conditions are narrow.
+ pub fn blocked_event_names(&self) -> Vec<(&str, &BTreeSet<String>)> {
+ self.per_event
+ .iter()
+ .filter(|(_, event)| !event.is_projection_eligible())
+ .map(|(name, event)| (name.as_str(), &event.blockers))
+ .collect()
+ }
+
+ /// The blocked event names and their reasons as one compact line, for the per-run log.
+ ///
+ /// Capped at [`MAX_RENDERED_BLOCKED_EVENTS`], with the remainder counted rather than named. The
+ /// names are customer-defined and a catalog's event vocabulary has no ceiling, so an uncapped
+ /// line is a log entry whose size the operator does not control. The head is what gets acted
+ /// on; [`Self::render_all_blocked_events`] is where the elided names are.
+ pub fn render_blocked_events(&self) -> String {
+ let blocked = self.blocked_event_names();
+ let mut rendered =
+ render_event_sets(blocked.iter().take(MAX_RENDERED_BLOCKED_EVENTS).copied());
+ if let Some(elided) = blocked.len().checked_sub(MAX_RENDERED_BLOCKED_EVENTS) {
+ if elided > 0 {
+ rendered.push_str(&format!(" (+{elided} more)"));
+ }
+ }
+ rendered
+ }
+
+ /// Every blocked event name with its reasons, uncapped, for the per-run debug log.
+ ///
+ /// This is the list to join against per-event row volume, so a run whose blocked set outgrows
+ /// the capped line still has its whole set somewhere. The debug level is what makes the
+ /// uncapped size acceptable.
+ pub fn render_all_blocked_events(&self) -> String {
+ render_event_sets(self.blocked_event_names())
+ }
+
+ /// The read sets as one compact line per event name, for the per-run debug log. Events that
+ /// read nothing are absent; a blocked one is named by [`Self::render_all_blocked_events`].
+ pub fn render_reads(&self) -> String {
+ render_event_sets(
+ self.per_event
+ .iter()
+ .filter(|(_, event)| !event.reads.is_empty())
+ .map(|(event_name, event)| (event_name.as_str(), &event.reads)),
+ )
+ }
+}
+
+/// `name=[value,value] name=[value]` — the shape both per-event log lines render in.
+fn render_event_sets<'a>(
+ events: impl IntoIterator<Item = (&'a str, &'a BTreeSet<String>)>,
+) -> String {
+ events
+ .into_iter()
+ .map(|(event_name, values)| {
+ format!(
+ "{event_name}=[{}]",
+ values.iter().cloned().collect::<Vec<_>>().join(",")
+ )
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+#[cfg(test)]
+mod tests {
+ use cohort_core::filters::{CohortId, TeamFiltersBuilder, TeamId};
+ use serde_json::json;
+
+ use super::*;
+ use crate::domain::Lookback;
+
+ fn hash(value: &str) -> ConditionHash {
+ ConditionHash::parse(value).expect("test hashes are 16 ASCII bytes")
+ }
+
+ fn condition(hash_value: &str, event_name: &str) -> PinnedCondition {
+ PinnedCondition {
+ cohort_id: CohortId(1),
+ hash: hash(hash_value),
+ event_name: event_name.to_owned(),
+ lookback: Lookback::SlidingDays(7),
+ }
+ }
+
+ /// Build a frozen catalog holding one behavioral leaf per `(hash, event, bytecode)` triple.
+ fn filters(leaves: &[(&str, &str, serde_json::Value)]) -> TeamFilters {
+ let values = leaves
+ .iter()
+ .map(|(hash_value, event_name, bytecode)| {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": event_name,
+ "conditionHash": hash_value,
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": bytecode,
+ })
+ })
+ .collect::<Vec<_>>();
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(2),
+ &json!({ "properties": { "type": "AND", "values": values } }),
+ )
+ .expect("the test catalog parses");
+ builder.freeze(chrono_tz::UTC)
+ }
+
+ fn event_equality(event_name: &str) -> serde_json::Value {
+ json!(["_H", 1, 32, event_name, 32, "event", 1, 1, 11])
+ }
+
+ /// `properties.plan == 'paid' AND event == 'purchase'`, in the compiler's emission order.
+ fn property_condition() -> serde_json::Value {
+ json!([
+ "_H",
+ 1,
+ 32,
+ "paid",
+ 32,
+ "plan",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 11,
+ 32,
+ "purchase",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 3,
+ 2
+ ])
+ }
+
+ /// A bare `properties` root: understood, but every column is needed.
+ fn bare_properties() -> serde_json::Value {
+ json!(["_H", 1, 32, "properties", 1, 1, 35])
+ }
+
+ /// A `CALLABLE`, which introduces a frame the model refuses.
+ fn unanalyzable() -> serde_json::Value {
+ json!(["_H", 1, 52, "f", 0, 0, 0])
+ }
+
+ #[test]
+ fn each_bytecode_shape_lands_in_its_class_with_its_read_set() {
+ let conditions = [
+ condition("eventonly0000000", "purchase"),
+ condition("projectable00000", "signup"),
+ condition("fullcolumns00000", "checkout"),
+ condition("unanalyzable0000", "refund"),
+ ];
+ let catalog = filters(&[
+ ("eventonly0000000", "purchase", event_equality("purchase")),
+ ("projectable00000", "signup", property_condition()),
+ ("fullcolumns00000", "checkout", bare_properties()),
+ ("unanalyzable0000", "refund", unanalyzable()),
+ ]);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(census.count(ConditionClass::EventOnly), 1);
+ assert_eq!(census.count(ConditionClass::Projectable), 1);
+ assert_eq!(census.count(ConditionClass::FullColumns), 1);
+ assert_eq!(census.count(ConditionClass::Unanalyzable), 1);
+ assert_eq!(census.total(), 4);
+ // One projectable against one bare-root and one refused: the event-only condition is not a
+ // property filter and takes no part in the ratio.
+ assert_eq!(census.property_projectable_fraction(), 1.0 / 3.0);
+ assert_eq!(
+ census.unanalyzable_reasons,
+ BTreeMap::from([(
+ UnanalyzableLabel {
+ reason: "unsupported_op",
+ op: Some(Arc::from("Callable")),
+ },
+ 1
+ )])
+ );
+ assert_eq!(
+ census.projection_eligible_event_names(),
+ ["purchase", "signup"]
+ );
+ assert_eq!(
+ census.render_blocked_events(),
+ "checkout=[bare_properties_root] refund=[unsupported_op:Callable]"
+ );
+ // The event-only condition is still a narrow read, so its `event` read is reported too.
+ assert_eq!(
+ census.render_reads(),
+ "purchase=[event] signup=[event,properties.plan]"
+ );
+ }
+
+ /// One narrow and one wide condition on the same event name. A scan selects columns for the
+ /// whole event, so that event is not projection-eligible however narrow its other condition is.
+ /// Counting conditions alone would report it as half projectable and overstate the win on
+ /// exactly the busy events that carry several conditions.
+ #[test]
+ fn an_event_name_with_one_wide_condition_is_not_projection_eligible() {
+ let conditions = [
+ condition("narrow0000000000", "$pageview"),
+ condition("wide000000000000", "$pageview"),
+ ];
+ let catalog = filters(&[
+ ("narrow0000000000", "$pageview", property_condition()),
+ ("wide000000000000", "$pageview", bare_properties()),
+ ]);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(census.count(ConditionClass::Projectable), 1);
+ assert_eq!(census.count(ConditionClass::FullColumns), 1);
+ let event = &census.per_event["$pageview"];
+ assert_eq!(event.projectable, 1);
+ assert_eq!(event.unprojectable, 1);
+ assert!(!event.is_projection_eligible());
+ assert_eq!(census.projection_eligible_event_names(), Vec::<&str>::new());
+ assert_eq!(
+ census.blocked_event_names(),
+ [(
+ "$pageview",
+ &BTreeSet::from(["bare_properties_root".to_owned()])
+ )]
+ );
+ }
+
+ /// The opcode that stopped the analysis is carried alongside the coarse reason. Without it,
+ /// every branch, frame, and heap write reads as one "unsupported_op" bucket, and the census
+ /// cannot say whether the blocked conditions are one fixable compiler template or many.
+ #[test]
+ fn an_unsupported_opcode_is_reported_with_the_opcode() {
+ let conditions = [
+ condition("callable00000000", "a"),
+ condition("incohort00000000", "b"),
+ ];
+ let catalog = filters(&[
+ ("callable00000000", "a", unanalyzable()),
+ // `IN_COHORT` reads membership state that is not in the globals dict at all.
+ ("incohort00000000", "b", json!(["_H", 1, 29, 29, 27])),
+ ]);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(
+ census.unanalyzable_reasons,
+ BTreeMap::from([
+ (
+ UnanalyzableLabel {
+ reason: "unsupported_op",
+ op: Some(Arc::from("Callable")),
+ },
+ 1
+ ),
+ (
+ UnanalyzableLabel {
+ reason: "unsupported_op",
+ op: Some(Arc::from("InCohort")),
+ },
+ 1
+ ),
+ ])
+ );
+ assert_eq!(
+ census.render_blocked_events(),
+ "a=[unsupported_op:Callable] b=[unsupported_op:InCohort]"
+ );
+ }
+
+ /// A hash the frozen catalog carries no bytecode for never reached the analyzer, so it is
+ /// counted under its own reason rather than blamed on the analysis.
+ #[test]
+ fn a_condition_without_bytecode_is_counted_as_missing_rather_than_analyzed() {
+ let conditions = [condition("nobytecode000000", "purchase")];
+ let census = ConditionAnalyses::build(&conditions, &filters(&[])).census(&conditions);
+ assert_eq!(census.count(ConditionClass::Unanalyzable), 1);
+ assert_eq!(
+ census.unanalyzable_reasons,
+ BTreeMap::from([(UnanalyzableLabel::missing_bytecode(), 1)])
+ );
+ assert!(!census.per_event["purchase"].is_projection_eligible());
+ }
+
+ /// One condition shared by several cohorts is one piece of work. Counting it per pinned entry
+ /// would overstate the projectable share on exactly the catalogs where sharing is common.
+ #[test]
+ fn a_hash_shared_across_cohorts_is_counted_once() {
+ let shared = "shared0000000000";
+ let mut first = condition(shared, "purchase");
+ first.cohort_id = CohortId(1);
+ let mut second = condition(shared, "purchase");
+ second.cohort_id = CohortId(2);
+ let conditions = [first, second];
+ let catalog = filters(&[(shared, "purchase", event_equality("purchase"))]);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(census.total(), 1);
+ assert_eq!(census.count(ConditionClass::EventOnly), 1);
+ assert_eq!(census.per_event["purchase"].event_only, 1);
+ }
+
+ /// The same hash under two event names has to account against both. The hash and the event name
+ /// are independent fields of the Django payload, so nothing structural pairs them; a census that
+ /// skipped the repeat would leave the second event with no row, and an event whose only other
+ /// conditions are narrow would then read as projection-eligible while carrying a wide one.
+ #[test]
+ fn a_hash_reused_under_two_event_names_accounts_against_both() {
+ let shared = "shared0000000000";
+ let conditions = [condition(shared, "purchase"), condition(shared, "signup")];
+ let catalog = filters(&[(shared, "purchase", bare_properties())]);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(
+ census.blocked_event_names(),
+ [
+ (
+ "purchase",
+ &BTreeSet::from(["bare_properties_root".to_owned()])
+ ),
+ (
+ "signup",
+ &BTreeSet::from(["bare_properties_root".to_owned()])
+ ),
+ ]
+ );
+ }
+
+ /// Past the cap the info line counts the rest instead of naming them, and the uncapped
+ /// renderer still names every one. An event blocked only by a wide condition reads nothing, so
+ /// it is absent from the read dump; without the uncapped list it would appear in no output at
+ /// all, and the blocked set is the census's whole deliverable.
+ #[test]
+ fn blocked_events_past_the_cap_are_counted_in_the_info_line_and_named_in_full() {
+ let over_cap = MAX_RENDERED_BLOCKED_EVENTS + 3;
+ // Zero-padded so the rendered order matches the generated one.
+ let hashes = (0..over_cap)
+ .map(|index| format!("wide{index:012}"))
+ .collect::<Vec<_>>();
+ let names = (0..over_cap)
+ .map(|index| format!("event_{index:03}"))
+ .collect::<Vec<_>>();
+ let conditions = hashes
+ .iter()
+ .zip(&names)
+ .map(|(hash, name)| condition(hash, name))
+ .collect::<Vec<_>>();
+ let leaves = hashes
+ .iter()
+ .zip(&names)
+ .map(|(hash, name)| (hash.as_str(), name.as_str(), bare_properties()))
+ .collect::<Vec<_>>();
+ let catalog = filters(&leaves);
+
+ let census = ConditionAnalyses::build(&conditions, &catalog).census(&conditions);
+ assert_eq!(census.blocked_event_names().len(), over_cap);
+
+ let capped = census.render_blocked_events();
+ assert!(capped.ends_with(" (+3 more)"), "{capped}");
+ assert!(!capped.contains(&names[over_cap - 1]), "{capped}");
+
+ let full = census.render_all_blocked_events();
+ for name in &names {
+ assert!(full.contains(name), "{name} is named nowhere");
+ }
+ assert!(!full.contains("more)"), "the uncapped line does not elide");
+ // Nothing narrow was found, so the read dump cannot carry these names either.
+ assert_eq!(census.render_reads(), "");
+ }
+
+ #[test]
+ fn a_run_with_no_conditions_reports_an_empty_census() {
+ let census = ConditionAnalyses::default().census(&[]);
+ assert_eq!(census, ConditionCensus::default());
+ assert_eq!(census.total(), 0);
+ assert_eq!(census.property_projectable_fraction(), 0.0);
+ assert_eq!(census.render_reads(), "");
+ assert_eq!(census.render_blocked_events(), "");
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 56ee7a3e938b..85e3ede53263 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -12,6 +12,7 @@ pub mod backoff;
pub mod chunk;
pub mod completion;
pub mod condition;
+pub mod condition_analysis;
pub mod ids;
pub mod ledger;
pub mod partition;
@@ -42,6 +43,9 @@ pub use completion::{
SettleProof, UndispatchedReason, WatchPartition, WatchPositions,
};
pub use condition::{EventNameSet, Lookback, PinnedCondition};
+pub use condition_analysis::{
+ ConditionAnalyses, ConditionCensus, ConditionClass, MISSING_BYTECODE_REASON,
+};
pub use ids::{
Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,
ScannedAtMs, UtcMillis, UtcMsRange, UtcRangeError,
diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rs
index 2b06c6e87a91..0428cab47190 100644
--- a/rust/cohort-seeder/src/domain/pinned.rs
+++ b/rust/cohort-seeder/src/domain/pinned.rs
@@ -502,6 +502,7 @@ fn derive_lookback(
#[cfg(test)]
mod tests {
+ use super::super::condition_analysis::{ConditionAnalyses, ConditionClass};
use chrono::NaiveDate;
use chrono_tz::UTC;
use cohort_core::day_idx_of_naive_date;
@@ -917,6 +918,84 @@ mod tests {
);
}
+ /// A validated run classifies the same way every time it is validated. Determinism is what a
+ /// later projection pass depends on: a chunk retried on another replica re-validates the same
+ /// payload, and two replicas that disagreed about a condition's read set would scan two
+ /// different column sets for the same chunk.
+ #[test]
+ fn a_revalidated_run_classifies_its_conditions_identically() {
+ let event_only = "eventonly0000000";
+ let projectable = "projectable00000";
+ // `properties.plan == 'paid' AND event == 'signup'`, in the compiler's emission order.
+ let property_bytecode = json!([
+ "_H",
+ 1,
+ 32,
+ "paid",
+ 32,
+ "plan",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 11,
+ 32,
+ "signup",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 3,
+ 2
+ ]);
+ let catalog = json!({
+ "properties": { "type": "AND", "values": [
+ { "type": "behavioral", "value": "performed_event", "key": "purchase", "conditionHash": event_only, "time_value": 7, "time_interval": "day", "bytecode": bytecode("purchase") },
+ { "type": "behavioral", "value": "performed_event", "key": "signup", "conditionHash": projectable, "time_value": 7, "time_interval": "day", "bytecode": property_bytecode },
+ ]}
+ });
+ let payload = || {
+ let mut first = condition(1, event_only, "performed_event", Some("purchase"), 7);
+ first["time_value"] = json!(7);
+ first["time_interval"] = json!("day");
+ let mut second = condition(1, projectable, "performed_event", Some("signup"), 7);
+ second["time_value"] = json!(7);
+ second["time_interval"] = json!("day");
+ snapshot(
+ json!({
+ "schema_version": 1,
+ "conditions": [first, second],
+ "event_names": ["purchase", "signup"],
+ }),
+ vec![PinnedParticipation {
+ cohort_id: CohortId(1),
+ pinned_filters: catalog.clone(),
+ state: PinnedParticipationState::Active,
+ }],
+ )
+ };
+
+ let validated = PinnedRun::validate(payload()).unwrap().run;
+ let census = ConditionAnalyses::build(&validated.conditions, &validated.filters)
+ .census(&validated.conditions);
+ assert_eq!(census.count(ConditionClass::EventOnly), 1);
+ assert_eq!(census.count(ConditionClass::Projectable), 1);
+ assert_eq!(census.count(ConditionClass::FullColumns), 0);
+ assert_eq!(census.count(ConditionClass::Unanalyzable), 0);
+ assert_eq!(
+ census.render_reads(),
+ "purchase=[event] signup=[event,properties.plan]"
+ );
+
+ let revalidated = PinnedRun::validate(payload()).unwrap().run;
+ assert_eq!(
+ ConditionAnalyses::build(&revalidated.conditions, &revalidated.filters)
+ .census(&revalidated.conditions),
+ census
+ );
+ }
+
#[test]
fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_validation() {
let hash = "lenient000000000";
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 9c314478c325..29e52395ec27 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -15,6 +15,28 @@ pub const RUN_VALIDATION_FAILURES: &str = "seeder_run_validation_failures_total"
pub const TZ_FALLBACK: &str = "seeder_tz_fallback_total";
pub const CONDITIONS_DROPPED: &str = "seeder_conditions_dropped_total";
pub const LOOKBACK_TRUNCATED: &str = "seeder_lookback_truncated_total";
+/// Pinned behavioral conditions by what a static read of their bytecode found, labelled by `class`
+/// and `team_id` (counter). Counted once per run per unique condition hash, per stretch. Dark:
+/// nothing reads the analysis yet, so this reports what real catalogs look like before anything is
+/// built on it.
+///
+/// Read the class ratios, not the absolute totals: a restart re-counts every active run, and every
+/// replica counts every run, because the once-per-run gate is process-local. The paired `info!` line
+/// carries one run's exact numbers.
+///
+/// `team_id` names a team only while `REALTIME_COHORT_TEAM_ALLOWLIST` names few enough of them, and
+/// collapses to `other` otherwise. It is here because the question these counters answer is about
+/// one team's catalog; blended across teams they answer nobody's.
+pub const CONDITIONS_CLASSIFIED: &str = "seeder_conditions_classified_total";
+/// Conditions the static read could not narrow, labelled by a closed `reason`, the `op` that
+/// stopped it (`none` when no opcode did), and `team_id` (counter). Counted on the same
+/// once-per-run-per-stretch gate as [`CONDITIONS_CLASSIFIED`], and `team_id` collapses the same way.
+///
+/// Both label vocabularies are closed and never carry bytecode text: `reason` by construction, `op`
+/// because it is one of `Operation`'s 57 variant names. The opcode is worth a dimension because one
+/// fixable compiler template and a program nothing will ever narrow otherwise land in the same
+/// `unsupported_op` bucket.
+pub const CONDITIONS_UNANALYZABLE: &str = "seeder_conditions_unanalyzable_total";
pub const CHUNKS_PLANNED: &str = "seeder_chunks_planned_total";
pub const CHUNKS_CLAIMED: &str = "seeder_chunks_claimed_total";
pub const CHUNKS_RECLAIMED: &str = "seeder_chunks_reclaimed_total";
diff --git a/rust/common/hogvm/src/lib.rs b/rust/common/hogvm/src/lib.rs
index cd501accd90f..b8a872eb2800 100644
--- a/rust/common/hogvm/src/lib.rs
+++ b/rust/common/hogvm/src/lib.rs
@@ -18,6 +18,9 @@ pub use program::ExportedFunction;
pub use program::Module;
pub use program::Program;
+// The opcode vocabulary, for consumers that read bytecode without running it
+pub use ops::Operation;
+
// VM, and helpers
pub use vm::sync_execute;
pub use vm::HogVM;
diff --git a/rust/common/hogvm/src/ops.rs b/rust/common/hogvm/src/ops.rs
index bfdaee63032c..7e88e50a6aeb 100644
--- a/rust/common/hogvm/src/ops.rs
+++ b/rust/common/hogvm/src/ops.rs
@@ -3,7 +3,7 @@ use serde_json::Value;
use crate::error::VmError;
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "Value")]
pub enum Operation {
GetGlobal = 1,
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 332f22a1fb92..f3159e7234dd 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -1572,7 +1572,7 @@ fn op_telemetry_name(op: &Operation) -> String {
}
name.push(c.to_ascii_uppercase());
}
- format!("{}/{}", op.clone() as u8, name)
+ format!("{}/{}", *op as u8, name)
}
fn next_type_name(next: &JsonValue) -> String {