:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cohorts): a global root outside the globals claims no reads (#92567)
Matheus Batistaa0e17644c162
diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rsindex d43fc831353e..53cfa26351bd 100644--- a/rust/cohort-core/src/hogvm/analysis/mod.rs+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs@@ -11,12 +11,27 @@//! [`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.//!+//! One input is answered rather than widened: a `GET_GLOBAL` root outside [`GlobalRoot`] claims no+//! read. That is not an exception to the rule above, but a consequence of the section below — such+//! a root reads no event data at all. A root naming a representation-sensitive native still widens,+//! because it resolves to a closure the program can call.+//!//! # 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.+//!+//! A path whose root is outside [`GlobalRoot`] records nothing, which is sound because a projection+//! narrows the values *under* a root and never removes one. A name no globals dict carries is+//! absent from the projected event and from the full one alike, so it names no column. That rests+//! on [`GlobalRoot`] covering every dict this crate builds, which+//! `every_globals_dict_key_is_a_named_root` in `hogvm::globals` checks.+//!+//! Reading no event data is only half the obligation. A bare native name resolves to a closure+//! instead of a read, so such a root widens whenever calling it would read a value's spelling+//! rather than its value, the same way a direct call to it does.mod decode;mod event_only;@@ -108,8 +123,6 @@ pub enum UnanalyzableReason {/// 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,@@ -137,14 +150,13 @@ pub enum UnanalyzableReason {}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.+ /// A closed, bounded label. The payloads (an opcode, 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",@@ -160,9 +172,8 @@ impl UnanalyzableReason {/// 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.+ /// safe as a second metric dimension. 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.@@ -171,8 +182,7 @@ impl UnanalyzableReason {match self {Self::Decode(error) => error.op(),Self::UnsupportedOp(op) => Some(*op),- Self::UnknownGlobalRoot(_)- | Self::DynamicGlobalPath+ Self::DynamicGlobalPath| Self::StackUnderflow| Self::ZeroLengthGlobalChain| Self::StackDepthMismatch@@ -225,11 +235,16 @@ impl GroupIndex {}}-/// The roots of the behavioral globals dict, which is the whole surface a condition can read.+/// Every root of every globals dict this crate builds, which is the whole surface a condition can+/// read.+///+/// The list is load-bearing in one direction. A name outside it claims no read, so a key added to a+/// globals dict without a variant here would be pruned from a scan while the program still reads+/// it. `every_globals_dict_key_is_a_named_root` in `hogvm::globals` is what earns that: it walks+/// the dicts themselves rather than a list, so it fails as soon as one gains a key.///-/// 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.+/// The other direction is benign. A variant no dict carries over-claims a read, which costs bytes+/// and never correctness, so nothing here has to chase it.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]pub enum GlobalRoot {Event,@@ -247,10 +262,16 @@ pub enum GlobalRoot {DollarGroup(GroupIndex),Group(GroupIndex),Variables,+ /// Only in the person-scope dict, never in the behavioral one. Named here so that "not a+ /// [`GlobalRoot`]" means "in no globals dict this crate builds" rather than "in the behavioral+ /// one".+ Project,}impl GlobalRoot {- /// Resolve a literal root name. `None` means the name is not a behavioral global.+ /// Resolve a literal root name. `None` means no globals dict this crate builds carries the+ /// name — which the analysis reads as "this path touches no event data", so the scope of the+ /// `None` is what makes that sound.pub fn parse(name: &str) -> Option<Self> {match name {"event" => Some(Self::Event),@@ -266,6 +287,7 @@ impl GlobalRoot {"pdi" => Some(Self::Pdi),"distinct_id" => Some(Self::DistinctId),"variables" => Some(Self::Variables),+ "project" => Some(Self::Project),_ => name.strip_prefix("$group_").and_then(group_index)@@ -295,6 +317,7 @@ impl GlobalRoot {Self::DollarGroup(index) => DOLLAR_GROUP_NAMES[index.get() as usize],Self::Group(index) => GROUP_NAMES[index.get() as usize],Self::Variables => "variables",+ Self::Project => "project",}}}@@ -406,7 +429,7 @@ mod tests {}#[test]- fn every_behavioral_global_root_round_trips_through_its_name() {+ fn every_global_root_round_trips_through_its_name() {let roots = [GlobalRoot::Event,GlobalRoot::Uuid,@@ -421,6 +444,7 @@ mod tests {GlobalRoot::Pdi,GlobalRoot::DistinctId,GlobalRoot::Variables,+ GlobalRoot::Project,];for root in roots {assert_eq!(GlobalRoot::parse(root.as_str()), Some(root.clone()));diff --git a/rust/cohort-core/src/hogvm/analysis/projection.rs b/rust/cohort-core/src/hogvm/analysis/projection.rsindex aa7bfcc38a19..f6cc92ccfd6a 100644--- a/rust/cohort-core/src/hogvm/analysis/projection.rs+++ b/rust/cohort-core/src/hogvm/analysis/projection.rs@@ -29,6 +29,11 @@//! 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.+//!+//! One case answers rather than widens. A `GET_GLOBAL` root that no globals dict carries reads+//! nothing under any projection, so it claims no path and the walk continues. A bare+//! representation-sensitive native is the exception, because such a root is a closure the program+//! can still call — see [`Interpreter::get_global`].use std::collections::{BTreeSet, VecDeque};use std::sync::Arc;@@ -603,9 +608,25 @@ impl<'a> Interpreter<'a> {}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 one-element chain also resolves to a first-class closure over a native, and+ // `arrayMap` invokes that closure through `CALL_LOCAL`, so the `CallGlobal` arm never+ // sees the name. Reading a number's spelling is unsafe however the native is reached,+ // so [`REPRESENTATION_SENSITIVE_NATIVES`] has to be checked on both paths.+ if segments.is_empty() && REPRESENTATION_SENSITIVE_NATIVES.contains(&root_name.as_ref())+ {+ return Err(Stop::Unnarrowable(+ FullColumnsReason::RepresentationSensitiveCall,+ ));+ }+ // Every other such name reads no event data, so it constrains no column. A projection+ // narrows the values *under* the roots a globals builder writes and never removes a+ // root, so a name absent from the dict is absent under every projection: its+ // `GET_GLOBAL` raises `UnknownGlobal` on the projected event and on the full one alike.+ // [`GlobalRoot`] is what makes "not a root" mean "in no dict this crate builds".+ //+ // Opaque rather than terminate: the closure case keeps executing, so ending the path+ // here could prune a genuine later read. Over-approximating is the safe direction.+ return push_opaque(stack);};// 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@@ -791,6 +812,107 @@ mod tests {);}+ /// The shape a group-type-name filter compiles to. `organization` is a per-team group type: the+ /// SQL printer aliases it onto `group_0`, but the bytecode compiler emits the written chain+ /// verbatim, so the root reaches the VM and no globals dict carries it. Such a root reads no+ /// event data under any projection, so the program claims nothing.+ ///+ /// Written out literally rather than through the `read` helper, so the helper cannot hide the+ /// same mistake, for the same reason+ /// `a_global_chain_is_read_root_first_from_its_reversed_pushes` is written that way.+ #[test]+ fn a_root_no_globals_dict_carries_claims_no_reads() {+ // organization.properties.name == 'Example Org'+ let tokens = vec![+ json!(32),+ json!("Example Org"),+ json!(32),+ json!("name"),+ json!(32),+ json!("properties"),+ json!(32),+ json!("organization"),+ json!(1),+ json!(3),+ json!(11),+ ];+ assert_eq!(reads(tokens), Vec::<String>::new());+ }++ /// The absent root continues the walk rather than ending it, so a read after one is still+ /// claimed. A `Control::Terminate` implementation passes every other test in this file and+ /// fails only here.+ #[test]+ fn a_read_after_an_absent_root_is_still_claimed() {+ let mut tokens = read(&["organization"]);+ tokens.extend(read(&["properties", "plan"]));+ // `AND` of the two, so the program balances its stack the way the compiler would.+ tokens.push(json!(3));+ tokens.push(json!(2));+ assert_eq!(reads(tokens), ["properties.plan"]);+ }++ /// A bare native name is not a read. `GET_GLOBAL` resolves it to a first-class closure, and+ /// `arrayMap` invokes that closure through `CALL_LOCAL`, so the `CALL_GLOBAL` guard never sees+ /// the name. `typeof` answers from how a number was spelled, so a caller rebuilding the blob+ /// from the claimed keys re-prints `100.0` as `100` and the condition decides the other way.+ /// The root carries the same obligation a direct call does.+ #[test]+ fn a_representation_sensitive_native_reached_as_a_root_widens() {+ // arrayMap(typeof, [properties.n]) == ['float']+ let tokens = vec![+ json!(32),+ json!("typeof"),+ json!(1),+ json!(1),+ json!(32),+ json!("n"),+ json!(32),+ json!("properties"),+ json!(1),+ json!(2),+ json!(43),+ json!(1),+ json!(2),+ json!("arrayMap"),+ json!(2),+ json!(32),+ json!("float"),+ json!(43),+ json!(1),+ json!(11),+ ];+ assert_eq!(+ full_columns_reason(tokens),+ FullColumnsReason::RepresentationSensitiveCall+ );+ }++ /// A native the rebuild cannot disturb stays projectable when it arrives as a root, so the+ /// guard above widens on representation sensitivity rather than on every native reference.+ #[test]+ fn an_insensitive_native_reached_as_a_root_still_claims_its_reads() {+ // arrayMap(base64Encode, [properties.n])+ let tokens = vec![+ json!(32),+ json!("base64Encode"),+ json!(1),+ json!(1),+ json!(32),+ json!("n"),+ json!(32),+ json!("properties"),+ json!(1),+ json!(2),+ json!(43),+ json!(1),+ json!(2),+ json!("arrayMap"),+ json!(2),+ ];+ assert_eq!(reads(tokens), ["properties.n"]);+ }+/// `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.@@ -818,8 +940,8 @@ mod tests {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.+ /// A path segment computed at runtime, 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.@@ -832,10 +954,6 @@ mod tests {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::ZeroLengthGlobalChaindiff --git a/rust/cohort-core/src/hogvm/globals.rs b/rust/cohort-core/src/hogvm/globals.rsindex 0cb1690c6f1c..58e35554c6e0 100644--- a/rust/cohort-core/src/hogvm/globals.rs+++ b/rust/cohort-core/src/hogvm/globals.rs@@ -139,6 +139,8 @@ fn normalize_timestamp(raw: &str) -> String {#[cfg(test)]mod tests {+ use crate::hogvm::analysis::GlobalRoot;+use super::*;fn event() -> CohortStreamEvent {@@ -192,6 +194,33 @@ mod tests {}}+ /// Every root a globals dict carries has to be a [`GlobalRoot`], because the analyzer treats a+ /// name outside that enum as reading nothing. A key added here without a matching variant+ /// there would be pruned from a scan while the program still reads it.+ ///+ /// This walks the dicts rather than a list of names, unlike its neighbour above, which asserts+ /// `contains_key` over 23 names and so would not notice a 24th. That difference is what the+ /// test is for, and it means there is no list here to go stale.+ #[test]+ fn every_globals_dict_key_is_a_named_root() {+ let event = event();+ // `build_person_scan_globals` is absent because+ // `scan_globals_are_byte_equal_to_event_globals_for_equal_inputs` already pins its output+ // to `build_person_property_globals`, so its key set is covered here.+ for globals in [+ build_behavioral_globals(&event).unwrap(),+ build_person_property_globals(&event).unwrap(),+ ] {+ for key in globals.as_object().unwrap().keys() {+ assert!(+ GlobalRoot::parse(key).is_some(),+ "globals key `{key}` is not a GlobalRoot, so the analyzer would read a \+ condition naming it as reading nothing"+ );+ }+ }+ }+#[test]fn behavioral_globals_shape_matches_node() {let globals = build_behavioral_globals(&event()).unwrap();diff --git a/rust/cohort-core/tests/analysis_parity_corpus.rs b/rust/cohort-core/tests/analysis_parity_corpus.rsindex d1d379b99f72..d89138907c85 100644--- a/rust/cohort-core/tests/analysis_parity_corpus.rs+++ b/rust/cohort-core/tests/analysis_parity_corpus.rs@@ -15,8 +15,11 @@ 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};+use cohort_core::{+ build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortStreamEvent, EvalOutcome,+ VmErrorClass,+};+use serde_json::{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.@@ -231,3 +234,83 @@ fn the_branch_lowered_fixtures_narrow_to_a_read_set() {);}}++/// A production filter on `organization.properties.name`, where `organization` is a team-defined+/// group type. HogQL aliases such a name onto `group_0` when it prints SQL, but the bytecode+/// compiler emits the written chain, so the root reaches the VM and no globals dict carries it.+///+/// Not a `hogvm_parity` fixture: both runners of that directory panic on a non-`Matched` outcome,+/// and this program raises rather than returning a bool, so adding it there would break the+/// processor's parity suite.+///+/// The two halves together are the equivalence the fixtures assert for ordinary programs. The+/// analysis claims no reads, and the program decides the same way on the full globals as on the+/// empty projection those reads produce, because the absent root raises on both. What the condition+/// does is unchanged — it already collapses to `false` in production and counts an `unknown_ref`.+/// Only its classification moved.+#[test]+fn an_absent_group_type_root_claims_no_reads_and_raises_either_way() {+ // organization.properties.name == 'Example Org'+ let bytecode = vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!("Example Org"),+ json!(32),+ json!("name"),+ json!(32),+ json!("properties"),+ json!(32),+ json!("organization"),+ json!(1),+ json!(3),+ json!(11),+ Value::from(OP_RETURN),+ ];++ let projection = analyze_condition(&bytecode).projection;+ let Projection::Reads(paths) = projection else {+ panic!("a root no globals dict carries should claim a read set: {projection:?}");+ };+ assert!(+ paths.is_empty(),+ "claimed {:?} for a root that reads no event data",+ paths.iter().map(ReadPath::render).collect::<Vec<_>>()+ );++ let full = build_behavioral_globals(&event()).expect("the event's payloads are valid JSON");+ let projected = project_globals(&full, &paths);+ assert_eq!(+ projected,+ Value::Object(Map::new()),+ "an empty read set has to prune the globals to nothing"+ );+ for (shape, globals) in [("full", full), ("projected", projected)] {+ match evaluate_detailed(&bytecode, globals) {+ EvalOutcome::VmError(error) => assert_eq!(+ classify_vm_error(&error),+ VmErrorClass::UnknownReference,+ "the {shape} globals raised something other than an unknown reference: {error:?}"+ ),+ other => panic!("the {shape} globals did not raise: {other:?}"),+ }+ }+}++fn event() -> CohortStreamEvent {+ CohortStreamEvent {+ team_id: 42,+ person_id: "p-123".to_string(),+ distinct_id: "d-1".to_string(),+ uuid: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),+ event: "$pageview".to_string(),+ timestamp: "2026-05-26 12:34:56.789000".to_string(),+ properties: Some(r#"{"$browser":"Chrome"}"#.to_string()),+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),+ elements_chain: None,+ source_offset: 0,+ source_partition: 0,+ redirected_from: None,+ redirect_hops: 0,+ }+}diff --git a/rust/cohort-seeder/src/domain/projection.rs b/rust/cohort-seeder/src/domain/projection.rsindex eb5f8c4235f9..83c08a248c8e 100644--- a/rust/cohort-seeder/src/domain/projection.rs+++ b/rust/cohort-seeder/src/domain/projection.rs@@ -217,6 +217,10 @@ impl Demand {| GlobalRoot::DollarGroup(_)| GlobalRoot::Group(_)| GlobalRoot::Variables => {}+ // Absent from the behavioral globals entirely, so a behavioral condition naming it+ // raises however the scan was narrowed, and a person run never reaches a projection.+ // Either way it claims no column.+ GlobalRoot::Project => {}}}