:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): seed exact event property keys from materialized columns (#110364)
Matheus Batistae164e1dc02e3
diff --git a/docs/internal/realtime-cohorts/seeder.md b/docs/internal/realtime-cohorts/seeder.mdindex b64dc37c475f..d89ea3b55902 100644--- a/docs/internal/realtime-cohorts/seeder.md+++ b/docs/internal/realtime-cohorts/seeder.md@@ -127,6 +127,8 @@ WHERE team_id = <team>If none remain, the chunk is done without a query.- **Row filter.** When every active condition on an event name compares event properties to string values, only rows that can match one of them leave ClickHouse.See [Row filter](#row-filter).+- **Column-backed keys.** When every active condition reads its event properties only through exact string equalities, the scan reads them from materialized columns instead of the `properties` blob.+ See [Column-backed keys](#column-backed-keys).### Evaluating and producing@@ -288,7 +290,8 @@ Then each participation is marked complete, retryable, or superseded, and the ruA property blob comes back rebuilt with only the keys the conditions read.Without projection, most of the seeder's CPU goes to parsing JSON and assembling globals.In local measurements, a chunk ran about 3 times faster with keys rebuilt and about 60 times faster when no blob was needed.- Rebuilding keys costs ClickHouse more, so the gain is on the seeder's side.+ Rebuilding keys does not reduce what ClickHouse reads: the rebuild decompresses and parses the whole blob of every selected row, so the gain is on the seeder's side.+ Only [column-backed keys](#column-backed-keys) or an unread blob keep ClickHouse off the blob.On real data, projection raised client throughput per core by more than an order of magnitude.One side effect: a row whose skipped blob is malformed, which the live path would drop, is still evaluated here on its other fields.- **Shadow compare.**@@ -298,6 +301,8 @@ Then each participation is marked complete, retryable, or superseded, and the ruA chunk whose day has slid out of every active window issues no query.- **Row filter.**See [Row filter](#row-filter).+- **Column-backed keys.**+ See [Column-backed keys](#column-backed-keys).- **Bands.**Splitting a day by person hash bounds one chunk's memory, at the cost of reading the day once per band.- **Pacing.**@@ -368,13 +373,65 @@ Ingestion writes event properties with `JSON.stringify` of a parsed object, so a`tests/ch_event_row_filter.rs` checks all of this against a live ClickHouse, with the VM as the oracle.Where possible, the test reads a materialized column instead of the blob.-Before each filtered chunk, the seeder looks in `system.columns` for a `String` column of `sharded_events` whose default expression is exactly that extraction for the key, and that also exists on `events`.+Before each chunk with a row filter or [column-backed keys](#column-backed-keys), the seeder looks in `system.columns` for a `String` column of `sharded_events` whose default expression is exactly that extraction for the key, and that also exists on `events`.+The lookup serves both together, split into queries that each fit a GET.Only such a column is used, because a column with another expression, such as a typed `JSONExtract`, reads different values for the same row.The column holds '' for a blob ClickHouse cannot parse, so the test admits '' there instead of reading the blob.Without one, the test extracts from the blob: ClickHouse still decompresses the blob for the event's rows, but only the matching rows are transferred and evaluated.The filter is dropped when the query would grow past the 8192 bytes the client sends by GET, since the `cohort_seeder` profile refuses the POST form.`seeder_scan_row_filter_total{outcome}` reports per chunk whether the filter read materialized columns, read the blob, did not apply, or was dropped for length.+### Column-backed keys++A projected chunk rebuilds `properties` from the blob, so ClickHouse reads the whole blob of every selected row even when the conditions need one key.+When a materialized column can stand in for every projected key, the scan builds the object from the columns and never references the blob.+On local data with blobs of about 10 KB, the same scan read about 100 times fewer bytes this way.++A trim-quotes column holds the value's raw JSON text with a string's quotes removed, so it loses the JSON type.+The scan takes valid JSON text as it is and puts quotes back around anything else:++```sql+concat('{', '"$current_url":', if(isValidJSON(e.`mat_$current_url`), e.`mat_$current_url`, concat('"', e.`mat_$current_url`, '"')), '}')+```++That gives back every value except two kinds.+A string whose text is JSON comes back typed (`"5"` becomes `5`), and an absent key comes back as `""`.+HogVM equality gives the same answer for both only when the condition compares the key with a literal that is not empty, does not parse as a number, is not JSON text, and is not `true` or `false` in any case.++1. **Deciding per key.**+ The static pass that recognizes row filters also lists the keys each condition reads only through `properties.<key> == <literal>` with such a literal.+ A key qualifies on a chunk when every active condition that reads it is on that list for it.+2. **Deciding per chunk.**+ The scan uses columns only when every projected key qualifies and has a column.+ One key left on the blob would read the whole blob again.+ A column value that reads as `false` can be the boolean or the string `"false"`, and the VM equates the boolean with every literal that is not `true`.+ An over-counted tile stays, because the processor applies the larger of the live and seeded counts.+ So before it uses columns, the scan asks ClickHouse for one row of the chunk where such a column trims to `false`, which reads only the columns.+ If one exists, the chunk keeps the rebuild.+ The scan also keeps the rebuild when the column form makes the query too long to send by GET.+ When the column form and the row filter do not both fit, the row filter is dropped, because the columns keep ClickHouse off the blob for every row.+ The shadow compare's wide arm still reads the blob, so the compare checks the columns against it.++Some rows still differ, because the column has no type:++- **A blob ClickHouse cannot parse**, such as one holding an integer past 64 bits, stores `''` in every column, while `serde_json` reads the blob (under-count).+- **A string whose text is JSON nested deeper than 128 levels** comes back typed, so the rebuilt object fails to parse and the row is skipped (under-count).+- **A blob that does not parse at all, or whose root is an array**, still becomes an object, so the row is evaluated on its other globals where the live path drops it (over-count).+ This is the same over-count an unread blob takes, described under column projection.++`tests/ch_materialized_properties.rs` checks against a live ClickHouse that only these rows differ, with the VM as the oracle.+A column holds the first value of a repeated key where `serde_json` reads the last, which the row filter already assumes never happens.++A column must also be stored in the parts the scan reads.+ClickHouse computes a column added after the data was written from `properties` at read time, until a merge or `ALTER TABLE ... MATERIALIZE COLUMN` stores it.+The materializer backfills only `MATERIALIZE_COLUMNS_BACKFILL_PERIOD_DAYS`, which defaults to 0.+So check `system.parts_columns` for the lookback before a long run: an old partition without the column reads the blob as before.++`seeder_scan_properties_source_total{source}` reports per chunk where `properties` came from.+`columns` and `empty` keep ClickHouse off the blob.+`rebuilt_inexact_key`, `rebuilt_no_column`, `rebuilt_ambiguous_value` and `rebuilt_too_long` name why a chunk kept the rebuild, and `rebuilt_no_column` includes a failed or timed-out lookup.+A chunk that reads a key holding the boolean `false`, such as a flag response, counts under `rebuilt_ambiguous_value`.+### ClickHouse settingsThe client sends `max_execution_time`, the two external-spill byte thresholds, `max_bytes_in_set` and `join_algorithm` with every query.diff --git a/rust/cohort-core/src/hogvm/analysis/exactness.rs b/rust/cohort-core/src/hogvm/analysis/exactness.rsnew file mode 100644index 000000000000..faa4e1ba2bf9--- /dev/null+++ b/rust/cohort-core/src/hogvm/analysis/exactness.rs@@ -0,0 +1,81 @@+//! Whether a trim-quotes materialized column decides a `properties` key like the blob.++use std::collections::BTreeMap;+use std::ops::BitAnd;+use std::str::FromStr;++use hogvm::Num;+use serde_json::Value;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Exactness {+ Exact,+ Inexact,+}++impl Exactness {+ /// The column retypes JSON-looking strings and reads absent keys as `""`, so only a literal+ /// neither can equal is exact.+ pub fn of_literal(literal: &str) -> Self {+ let lowercase = literal.to_lowercase();+ let retyped = literal.is_empty()+ || Num::from_str(literal).is_ok()+ || serde_json::from_str::<Value>(literal).is_ok()+ || lowercase == "true"+ || lowercase == "false";+ if retyped {+ Self::Inexact+ } else {+ Self::Exact+ }+ }+}++impl BitAnd for Exactness {+ type Output = Self;++ fn bitand(self, other: Self) -> Self {+ match (self, other) {+ (Self::Exact, Self::Exact) => Self::Exact,+ (Self::Exact | Self::Inexact, Self::Inexact) | (Self::Inexact, Self::Exact) => {+ Self::Inexact+ }+ }+ }+}++/// Collecting keeps a key exact only while every read of it is.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ColumnExactness(BTreeMap<String, Exactness>);++impl ColumnExactness {+ pub fn get(&self, key: &str) -> Option<Exactness> {+ self.0.get(key).copied()+ }++ pub fn exact_keys(&self) -> impl Iterator<Item = &str> {+ self.0+ .iter()+ .filter(|(_, exactness)| **exactness == Exactness::Exact)+ .map(|(key, _)| key.as_str())+ }+}++impl<K: Into<String>> FromIterator<(K, Exactness)> for ColumnExactness {+ fn from_iter<I: IntoIterator<Item = (K, Exactness)>>(reads: I) -> Self {+ let mut by_key = BTreeMap::new();+ for (key, exactness) in reads {+ by_key+ .entry(key.into())+ .and_modify(|seen: &mut Exactness| *seen = *seen & exactness)+ .or_insert(exactness);+ }+ Self(by_key)+ }+}++impl FromIterator<ColumnExactness> for ColumnExactness {+ fn from_iter<I: IntoIterator<Item = ColumnExactness>>(maps: I) -> Self {+ maps.into_iter().flat_map(|map| map.0).collect()+ }+}diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rsindex 4a9968c5bab9..c681b0c65470 100644--- a/rust/cohort-core/src/hogvm/analysis/mod.rs+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs@@ -38,6 +38,7 @@mod decode;mod event_only;+mod exactness;mod plan;mod projection;mod row_filter;@@ -48,9 +49,10 @@ use hogvm::Operation;use serde_json::Value;pub use decode::DecodeError;+pub use exactness::{ColumnExactness, Exactness};pub use plan::{GlobalsBuild, GlobalsPlan};pub use projection::AnalysisBudget;-pub use row_filter::{event_row_filter, EventRowFilter, PropertyAlternatives};+pub use row_filter::{event_equalities, EventEqualities, EventRowFilter, PropertyAlternatives};/// What a static pass could establish about one condition's bytecode.#[derive(Debug, Clone, PartialEq, Eq)]diff --git a/rust/cohort-core/src/hogvm/analysis/projection.rs b/rust/cohort-core/src/hogvm/analysis/projection.rsindex f6cc92ccfd6a..cc4a0e5065d6 100644--- a/rust/cohort-core/src/hogvm/analysis/projection.rs+++ b/rust/cohort-core/src/hogvm/analysis/projection.rs@@ -46,7 +46,7 @@ use super::{FullColumnsReason, GlobalRoot, Projection, ReadPath, UnanalyzableRea/// `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";+pub(super) const ELEMENTS_CHAIN_PROPERTY: &str = "$elements_chain";/// Natives whose result depends on how a JSON number was spelled, rather than on its value.///diff --git a/rust/cohort-core/src/hogvm/analysis/row_filter.rs b/rust/cohort-core/src/hogvm/analysis/row_filter.rsindex d329d29d87e4..e5a787263387 100644--- a/rust/cohort-core/src/hogvm/analysis/row_filter.rs+++ b/rust/cohort-core/src/hogvm/analysis/row_filter.rs@@ -13,6 +13,15 @@ use hogvm::{Num, Operation};use serde_json::Value;use super::decode::{decode, InstrKind};+use super::exactness::{ColumnExactness, Exactness};+use super::projection::ELEMENTS_CHAIN_PROPERTY;++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct EventEqualities {+ pub row_filter: Option<EventRowFilter>,+ /// `None` when the program reads the whole object or the grammar does not parse it.+ pub column_exactness: Option<ColumnExactness>,+}/// A necessary condition for the program to return true: the row's `event` is [`Self::event`], and/// every conjunct has some `(key, value)` with `properties[key] == value` under HogVM equality.@@ -48,19 +57,100 @@ enum Node {key: Arc<str>,value: Arc<str>,},- OtherEquality,+ /// Any other `==`, kept for the `properties` reads in its operands.+ OtherEquality(Box<Node>, Box<Node>),And(Vec<Node>),Or(Vec<Node>),}+enum PropertyRead<'a> {+ Compared {+ key: &'a str,+ literal: &'a str,+ },+ /// Any other read of the key, including a path under it.+ Other {+ key: &'a str,+ },+ WholeObject,+}++impl<'a> PropertyRead<'a> {+ fn exactness(self) -> Option<(&'a str, Exactness)> {+ match self {+ Self::Compared { key, literal } => Some((key, Exactness::of_literal(literal))),+ Self::Other { key } => Some((key, Exactness::Inexact)),+ Self::WholeObject => None,+ }+ }++ fn of_chain(chain: &'a [Arc<str>]) -> Option<Self> {+ match chain {+ [root] if &**root == "properties" => Some(Self::WholeObject),+ [root, key, ..] if &**root == "properties" => Some(Self::Other { key }),+ // `elements_chain` falls back to this property.+ [root, ..] if &**root == "elements_chain" => Some(Self::Other {+ key: ELEMENTS_CHAIN_PROPERTY,+ }),+ _ => None,+ }+ }+}+impl Node {const fn is_boolean(&self) -> bool {!matches!(self, Self::Literal(_) | Self::Global(_))}++ fn property_reads(&self) -> PropertyReads<'_> {+ PropertyReads {+ pending: vec![self],+ }+ }}-pub fn event_row_filter(bytecode: &[Value]) -> Option<EventRowFilter> {- let root = parse(bytecode)?;+struct PropertyReads<'a> {+ pending: Vec<&'a Node>,+}++impl<'a> Iterator for PropertyReads<'a> {+ type Item = PropertyRead<'a>;++ fn next(&mut self) -> Option<Self::Item> {+ while let Some(node) = self.pending.pop() {+ match node {+ Node::Literal(_) | Node::EventIs(_) => {}+ Node::Global(chain) => {+ if let Some(read) = PropertyRead::of_chain(chain) {+ return Some(read);+ }+ }+ Node::PropertyIs { key, value } => {+ return Some(PropertyRead::Compared {+ key,+ literal: value,+ })+ }+ Node::OtherEquality(left, right) => self.pending.extend([&**left, &**right]),+ Node::And(operands) | Node::Or(operands) => self.pending.extend(operands),+ }+ }+ None+ }+}++pub fn event_equalities(bytecode: &[Value]) -> EventEqualities {+ let Some(root) = parse(bytecode) else {+ return EventEqualities::default();+ };+ EventEqualities {+ // A literal comparison keeps its answer under any `==`, `AND` or `OR` above it.+ column_exactness: root.property_reads().map(PropertyRead::exactness).collect(),+ row_filter: row_filter(root),+ }+}++fn row_filter(root: Node) -> Option<EventRowFilter> {let mut conjuncts = Vec::new();flatten_and(root, &mut conjuncts);@@ -145,19 +235,19 @@ fn parse(bytecode: &[Value]) -> Option<Node> {}fn equality(left: Node, right: Node) -> Node {- let (literal, chain) = match (left, right) {+ let recognized = match (&left, &right) {(Node::Literal(literal), Node::Global(chain))- | (Node::Global(chain), Node::Literal(literal)) => (literal, chain),- _ => return Node::OtherEquality,- };- match chain.as_slice() {- [root] if &**root == "event" => Node::EventIs(literal),- [root, key] if &**root == "properties" => Node::PropertyIs {- key: key.clone(),- value: literal,+ | (Node::Global(chain), Node::Literal(literal)) => match chain.as_slice() {+ [root] if &**root == "event" => Some(Node::EventIs(literal.clone())),+ [root, key] if &**root == "properties" => Some(Node::PropertyIs {+ key: key.clone(),+ value: literal.clone(),+ }),+ _ => None,},- _ => Node::OtherEquality,- }+ _ => None,+ };+ recognized.unwrap_or_else(|| Node::OtherEquality(Box::new(left), Box::new(right)))}fn flatten_and(node: Node, out: &mut Vec<Node>) {@@ -376,7 +466,11 @@ mod tests {),];for (label, body, expected) in cases {- assert_eq!(event_row_filter(&program(body)), Some(expected), "{label}");+ assert_eq!(+ event_equalities(&program(body)).row_filter,+ Some(expected),+ "{label}"+ );}}@@ -454,15 +548,227 @@ mod tests {),];for (label, body) in cases {- assert_eq!(event_row_filter(&program(body)), None, "{label}");+ assert_eq!(event_equalities(&program(body)).row_filter, None, "{label}");}let mut unterminated = program(fold(AND, vec![event_is("e"), property_is("k", "v")]));unterminated.pop();- assert_eq!(event_row_filter(&unterminated), None, "no RETURN");+ assert_eq!(+ event_equalities(&unterminated),+ EventEqualities::default(),+ "no RETURN"+ );let mut trailing = program(fold(AND, vec![event_is("e"), property_is("k", "v")]));trailing.push(json!(Operation::True as u64));- assert_eq!(event_row_filter(&trailing), None, "code after RETURN");+ assert_eq!(+ event_equalities(&trailing),+ EventEqualities::default(),+ "code after RETURN"+ );+ }++ fn exact_keys(body: Vec<Value>) -> BTreeSet<String> {+ event_equalities(&program(body))+ .column_exactness+ .map(|keys| keys.exact_keys().map(str::to_owned).collect())+ .unwrap_or_default()+ }++ #[test]+ fn a_key_is_column_exact_only_when_every_read_compares_it_with_an_exact_literal() {+ let under_the_key = vec![+ json!(STRING),+ json!("v"),+ json!(STRING),+ json!("sub"),+ json!(STRING),+ json!("k"),+ json!(STRING),+ json!("properties"),+ json!(GET_GLOBAL),+ json!(3),+ json!(EQ),+ ];+ let against_the_event = vec![+ json!(STRING),+ json!("k"),+ json!(STRING),+ json!("properties"),+ json!(GET_GLOBAL),+ json!(2),+ json!(STRING),+ json!("event"),+ json!(GET_GLOBAL),+ json!(1),+ json!(EQ),+ ];+ let the_elements_chain = vec![+ json!(STRING),+ json!("x"),+ json!(STRING),+ json!("elements_chain"),+ json!(GET_GLOBAL),+ json!(1),+ json!(EQ),+ ];+ let the_whole_object = vec![+ json!(STRING),+ json!("v"),+ json!(STRING),+ json!("properties"),+ json!(GET_GLOBAL),+ json!(1),+ json!(EQ),+ ];+ let pattern = {+ let mut tokens = property_is("k", "%v%");+ *tokens.last_mut().unwrap() = json!(Operation::Ilike as u64);+ tokens+ };+ let cases: Vec<(&str, Vec<Value>, &[&str])> = vec![+ (+ "one exact literal",+ fold(+ AND,+ vec![event_is("e"), property_is("k", "https://example.com/")],+ ),+ &["k"],+ ),+ (+ "a value list",+ fold(+ AND,+ vec![+ event_is("e"),+ fold(OR, vec![property_is("k", "a"), property_is("k", "b")]),+ ],+ ),+ &["k"],+ ),+ (+ "an inexact literal beside an exact one",+ fold(+ AND,+ vec![+ event_is("e"),+ fold(OR, vec![property_is("k", "a"), property_is("k", "TRUE")]),+ property_is("j", "b"),+ ],+ ),+ &["j"],+ ),+ (+ "a path under the key",+ fold(+ AND,+ vec![+ event_is("e"),+ property_is("k", "v"),+ under_the_key,+ property_is("j", "b"),+ ],+ ),+ &["j"],+ ),+ (+ "the key compared with another global",+ fold(+ AND,+ vec![+ event_is("e"),+ property_is("k", "v"),+ against_the_event,+ property_is("j", "b"),+ ],+ ),+ &["j"],+ ),+ (+ "an OR with a person property, which no row filter covers",+ fold(+ AND,+ vec![+ event_is("e"),+ fold(+ OR,+ vec![property_is("k", "v"), person_property_is("plan", "pro")],+ ),+ ],+ ),+ &["k"],+ ),+ (+ "the elements chain, which falls back to its property",+ fold(+ AND,+ vec![+ event_is("e"),+ property_is("$elements_chain", "a"),+ the_elements_chain,+ property_is("j", "b"),+ ],+ ),+ &["j"],+ ),+ (+ "the whole object",+ fold(+ AND,+ vec![event_is("e"), property_is("j", "b"), the_whole_object],+ ),+ &[],+ ),+ (+ "a program outside the grammar",+ fold(AND, vec![event_is("e"), property_is("j", "b"), pattern]),+ &[],+ ),+ ];+ for (label, body, expected) in cases {+ let expected: BTreeSet<String> = expected.iter().map(|key| (*key).to_owned()).collect();+ assert_eq!(exact_keys(body), expected, "{label}");+ }++ for literal in [+ "", "5", "-1", "1e3", "inf", "true", "TRUE", "False", "null", "{}", "[1]", "\"q\"",+ " 5",+ ] {+ let body = fold(AND, vec![event_is("e"), property_is("k", literal)]);+ assert_eq!(exact_keys(body), BTreeSet::new(), "{literal:?}");+ }+ }++ /// Mirrors `replaceRegexpAll(JSONExtractRaw(properties, key), '^"|"$', '')`.+ fn trim_quotes(raw: &str) -> &str {+ let raw = raw.strip_prefix('"').unwrap_or(raw);+ raw.strip_suffix('"').unwrap_or(raw)+ }++ /// Mirrors `if(isValidJSON(m), m, concat('"', m, '"'))`.+ fn rebuild(column: &str) -> Value {+ serde_json::from_str(column).unwrap_or_else(|_| {+ serde_json::from_str(&format!("\"{column}\""))+ .expect("a string's escaped body is a valid string once quoted again")+ })+ }++ fn exact_literal() -> impl Strategy<Value = String> {+ prop_oneof![+ Just("my-flag".to_owned()),+ Just("https://example.com/p?q=1".to_owned()),+ Just("2024-01-01".to_owned()),+ Just("a\"b\\c\n".to_owned()),+ Just("é😀".to_owned()),+ // Exact, but close to retyped text.+ Just("True ".to_owned()),+ Just("5a".to_owned()),+ Just("nul".to_owned()),+ Just("[".to_owned()),+ "\\PC{1,6}",+ ]+ .prop_filter("a literal a column decides exactly", |literal| {+ Exactness::of_literal(literal) == Exactness::Exact+ })}fn property_value() -> impl Strategy<Value = Value> {@@ -479,6 +785,13 @@ mod tests {Just(String::new()),Just("2024-01-01".to_owned()),Just("a\"b\\c\n".to_owned()),+ // Retyped by a trim-quotes column.+ Just("5".to_owned()),+ Just("5.0".to_owned()),+ Just("null".to_owned()),+ Just("[1]".to_owned()),+ Just("{}".to_owned()),+ Just(" 5".to_owned()),"\\PC{0,6}",].prop_map(Value::String),@@ -519,7 +832,7 @@ mod tests {AND,vec![event_is("e"), property_is("k", &expected)],));- let Some(row_filter) = event_row_filter(&bytecode) else {+ let Some(row_filter) = event_equalities(&bytecode).row_filter else {prop_assert!(Num::from_str(&expected).is_ok());return Ok(());};@@ -534,5 +847,43 @@ mod tests {prop_assert!(admitted, "the VM matched {actual} against {expected:?}");}}++ /// The string `"false"` is excluded: the column returns it as the boolean.+ #[test]+ fn an_exact_literal_answers_a_column_rebuilt_value_like_the_stored_one(+ actual in prop::option::of(property_value()),+ literal in exact_literal(),+ ) {+ let reads_as_false = |text: &str| {+ serde_json::from_str::<Value>(text).is_ok_and(|value| value == Value::Bool(false))+ };+ prop_assume!(!matches!(&actual, Some(Value::String(text)) if reads_as_false(text)));+ let bytecode = program(fold(AND, vec![event_is("e"), property_is("k", &literal)]));+ prop_assert_eq!(+ event_equalities(&bytecode).column_exactness.and_then(|keys| keys.get("k")),+ Some(Exactness::Exact)+ );++ let column = actual+ .as_ref()+ .map_or_else(String::new, |value| trim_quotes(&value.to_string()).to_owned());+ let stored = match &actual {+ Some(value) => json!({"event": "e", "properties": {"k": value}}),+ None => json!({"event": "e", "properties": {}}),+ };+ let rebuilt = json!({"event": "e", "properties": {"k": rebuild(&column)}});+ let verdict = |globals| match evaluate_detailed(&bytecode, globals) {+ EvalOutcome::Matched(matched) => matched,+ other => panic!("an equality program failed to evaluate: {other:?}"),+ };+ prop_assert_eq!(+ verdict(stored),+ verdict(rebuilt),+ "{:?} against {:?} through the column value {:?}",+ actual,+ literal,+ column+ );+ }}}diff --git a/rust/cohort-seeder/src/clickhouse/materialized.rs b/rust/cohort-seeder/src/clickhouse/materialized.rsindex bc61560a1248..dd2687741a18 100644--- a/rust/cohort-seeder/src/clickhouse/materialized.rs+++ b/rust/cohort-seeder/src/clickhouse/materialized.rs@@ -1,5 +1,5 @@-//! Finds the materialized columns a behavioral scan's row filter can read instead of the-//! `properties` blob.+//! Finds the materialized columns a behavioral scan's row filter and projection can read instead of+//! the `properties` blob.//!//! A column qualifies only when its stored default expression on the data table is exactly the//! trim-quotes extraction the filter would otherwise evaluate. A typed `JSONExtract` column reads@@ -7,56 +7,46 @@//! match. The column must also exist on the distributed `events` table the scan reads.use std::collections::{BTreeSet, HashMap};+use std::iter;use clickhouse::Row;use serde::Deserialize;use super::client::ClickHouseClient;-use super::sql::clickhouse_string_literal;+use super::sql::{clickhouse_string_literal, fits_client_get};+use crate::domain::MaterializedColumns;/// Only the data table's columns carry the default expressions.const EVENTS_DATA_TABLE: &str = "sharded_events";-/// Property key to verified column name.-#[derive(Debug, Clone, Default, PartialEq, Eq)]-pub struct MaterializedColumns(HashMap<String, String>);-impl MaterializedColumns {- pub fn column_for(&self, key: &str) -> Option<&str> {- self.0.get(key).map(String::as_str)- }-pub async fn lookup(client: &ClickHouseClient,keys: &BTreeSet<&str>,) -> Result<Self, clickhouse::error::Error> {- if keys.is_empty() {- return Ok(Self::default());- }- let expected: HashMap<String, &str> = keys+ let key_by_expression: HashMap<String, &str> = keys.iter().map(|key| (trim_quotes_extraction(key), *key)).collect();- let rows = client- .query(&lookup_sql(expected.keys()))- .fetch_all::<ColumnRow>()- .await?;- let mut columns = HashMap::new();- for row in rows {- // Rows are sorted by name, so every chunk picks the same column for a key.- if let Some(key) = expected.get(&row.expression) {- columns- .entry((*key).to_owned())- .or_insert_with(|| row.name.clone());- }+ let mut expressions = key_by_expression+ .keys()+ .map(String::as_str)+ .collect::<Vec<_>>();+ expressions.sort_unstable();+ let mut rows = Vec::new();+ for batch in lookup_batches(&expressions) {+ rows.extend(+ client+ .query(&lookup_sql(&batch))+ .fetch_all::<ColumnRow>()+ .await?,+ );}- Ok(Self(columns))- }-}--impl FromIterator<(String, String)> for MaterializedColumns {- fn from_iter<I: IntoIterator<Item = (String, String)>>(pairs: I) -> Self {- Self(pairs.into_iter().collect())+ // Rows are sorted by name, so every chunk picks the same column for a key.+ Ok(rows+ .into_iter()+ .filter_map(|row| Some((*key_by_expression.get(&row.expression)?, row.name)))+ .collect())}}@@ -74,14 +64,29 @@ fn trim_quotes_extraction(key: &str) -> String {format!("replaceRegexpAll(JSONExtractRaw(properties, '{escaped}'), '^\"|\"$', '')")}-fn lookup_sql<'a>(expressions: impl Iterator<Item = &'a String>) -> String {- let mut expressions = expressions+/// Each batch fits a GET, because the `cohort_seeder` profile refuses the POST form.+fn lookup_batches<'a>(expressions: &'a [&'a str]) -> impl Iterator<Item = Vec<&'a str>> + 'a {+ let mut pending = expressions.iter().copied().peekable();+ iter::from_fn(move || {+ let mut batch = vec![pending.next()?];+ while let Some(expression) = pending+ .next_if(|next| fits_client_get(&lookup_sql(&[batch.as_slice(), &[*next]].concat())))+ {+ batch.push(expression);+ }+ Some(batch)+ })+}++fn lookup_sql(expressions: &[&str]) -> String {+ let mut literals = expressions+ .iter().map(|expression| clickhouse_string_literal(expression)).collect::<Vec<_>>();- expressions.sort();+ literals.sort();format!("SELECT name, default_expression AS expression\nFROM system.columns\nWHERE database = currentDatabase() AND table = '{EVENTS_DATA_TABLE}'\n AND type = 'String' AND default_kind IN ('DEFAULT', 'MATERIALIZED')\n AND default_expression IN ({})\n AND name IN (SELECT name FROM system.columns WHERE database = currentDatabase() AND table = 'events' AND type = 'String')\nORDER BY name",- expressions.join(", "),+ literals.join(", "),)}@@ -89,6 +94,25 @@ fn lookup_sql<'a>(expressions: impl Iterator<Item = &'a String>) -> String {mod tests {use super::*;+ #[test]+ fn a_long_lookup_is_split_into_queries_that_each_fit_a_get() {+ let expressions = (0..300)+ .map(|index| trim_quotes_extraction(&format!("$feature/a-long-flag-name-{index:03}")))+ .collect::<Vec<_>>();+ let mut sorted = expressions.iter().map(String::as_str).collect::<Vec<_>>();+ sorted.sort_unstable();++ let batches = lookup_batches(&sorted).collect::<Vec<_>>();+ assert!(+ batches.len() > 1,+ "the keys fit one query, so nothing was split"+ );+ for batch in &batches {+ assert!(fits_client_get(&lookup_sql(batch)));+ }+ assert_eq!(batches.concat(), sorted);+ }+#[test]fn the_expected_expression_is_the_stored_materializer_text() {assert_eq!(diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rsindex cb5a0cd500bc..04c5e638d6c5 100644--- a/rust/cohort-seeder/src/clickhouse/scanner.rs+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs@@ -2,6 +2,7 @@//! evaluator into tiles, and emits the scan metrics. Depends on `domain`, `config`, and the sibling//! `sql`/`row` modules; never on `store` or `kafka`.+use std::collections::BTreeSet;use std::sync::Arc;use std::time::Duration;@@ -20,21 +21,24 @@ use tracing::{info, warn};use super::client::ClickHouseClient;use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};-use super::materialized::MaterializedColumns;use super::row::{row_to_event, EventRow};use super::scan_volume::{self, ScanKind};-use super::sql::{fits_client_get, plan_scan, row_filter_sql, scan_sql, ScanPlan, ScanSpec};+use super::sql::{+ ambiguous_value_probe_sql, fits_client_get, plan_scan, row_filter_sql, scan_sql, ScanPlan,+ ScanSpec,+};use crate::domain::{- conditions_active_on, diff_tiles, ActiveConditions, AggregateError, BlobSource, CancelCause,- ChunkAccumulator, ChunkDomainError, ChunkProjection, ChunkSpec, ClaimedChunk,- ConditionAnalyses, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun, RecordOutcome,- RecordStats, ScanRowFilter, ScanVolume, ScannedChunk, SeedDomain, SeedTile, TileDiff,+ conditions_active_on, diff_tiles, ActiveConditions, AggregateError, CancelCause,+ ChunkAccumulator, ChunkDomainError, ChunkProjection, ChunkSpec, ClaimedChunk, ColumnExactKeys,+ ColumnUpgrade, ConditionAnalyses, DayIdx, EventNameSet, Halted, MaterializedColumns,+ PinnedCondition, PinnedRun, ProjectedKeys, PropertiesSourcing, RecordOutcome, RecordStats,+ ScanRowFilter, ScanVolume, ScannedChunk, SeedDomain, SeedTile, SourcedProjection, TileDiff,UtcMillis,};use crate::observability::metrics::{team_label, MetricTimer, AGGREGATE_ENTRIES, CHUNKS_PROJECTED, CHUNKS_VACUOUS,CHUNK_SCAN_DURATION_SECONDS, CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS,- PROJECTION_KEYS, ROWS_SCANNED, SCAN_ROW_FILTER, SHADOW_COMPARE,+ PROJECTION_KEYS, ROWS_SCANNED, SCAN_PROPERTIES_SOURCE, SCAN_ROW_FILTER, SHADOW_COMPARE,SHADOW_COMPARE_DURATION_SECONDS, SHADOW_COMPARE_LEGACY_SKIPPED,};@@ -137,11 +141,26 @@ impl ChunkScanner {}};let projection = analyses.projection(&active);- self.record_projection(run.team_id, &projection);+ let exact = analyses.column_exact_keys(&active);let row_filter = analyses.row_filter(&event_names, &run.filters, &active);- let scan_spec = self- .filter_rows(run.team_id, scan_spec, &row_filter, &projection)+ let columns = self+ .lookup_columns(&column_lookup_keys(&projection, &exact, &row_filter)).await;+ let comment = ScanLogComment::BehavioralChunk {+ spec,+ cohort_id: run.sole_cohort_id(),+ };+ let sourcing = match projection.source_properties(&exact, &columns) {+ PropertiesSourcing::Upgradable(upgrade) => {+ self.probe_ambiguous_values(&scan_spec, upgrade, comment, lease_cancel, shutdown)+ .await?+ }+ decided @ PropertiesSourcing::Decided(_) => decided,+ };+ let narrowed = narrow_scan(scan_spec, sourcing, &row_filter, &columns);+ self.record_narrowing(run.team_id, &narrowed);+ let scan_spec = narrowed.filtered.spec;+ let projection = narrowed.sourced.into_projection();let (tiles, volume, projected_fold) = self.scan_once(@@ -152,10 +171,7 @@ impl ChunkScanner {&scan_spec,&projection,ScanKind::Behavioral,- ScanLogComment::BehavioralChunk {- spec,- cohort_id: run.sole_cohort_id(),- },+ comment,lease_cancel,shutdown,)@@ -342,88 +358,177 @@ impl ChunkScanner {Ok(())}- /// Drops the filter when the query would be too long to send, since every attempt would fail.- async fn filter_rows(+ /// The column form reads a column value that trims to `false` as the boolean, which the VM+ /// equates with every exact literal, while the string `"false"` equals none. Only the blob holds+ /// the type, so a chunk with such a value keeps the rebuild.+ async fn probe_ambiguous_values(&self,- team_id: TeamId,- spec: ScanSpec,- row_filter: &ScanRowFilter,- projection: &ChunkProjection,- ) -> ScanSpec {- let (spec, outcome) = if row_filter.is_empty() {- (spec, RowFilterOutcome::None)- } else {- let keys = row_filter.keys();- let columns = match tokio::time::timeout(- MATERIALIZED_LOOKUP_TIMEOUT,- MaterializedColumns::lookup(&self.client, &keys),- )- .await- {- Ok(Ok(columns)) => columns,- Ok(Err(error)) => {- warn!(error = ?error, "materialized column lookup failed; the row filter reads the properties blob");- MaterializedColumns::default()- }- Err(_) => {- warn!("materialized column lookup timed out; the row filter reads the properties blob");- MaterializedColumns::default()- }- };- let outcome = if keys.iter().all(|key| columns.column_for(key).is_some()) {- RowFilterOutcome::Materialized- } else {- RowFilterOutcome::PropertiesBlob- };- let filtered = spec- .clone()- .with_row_filter(row_filter_sql(row_filter, &columns));- // Both renderings, because the shadow compare sends the wide one with the same filter.- let fits = [projection, &ChunkProjection::FullColumns]- .into_iter()- .all(|projection| fits_client_get(&scan_sql(&filtered, projection)));- if fits {- (filtered, outcome)- } else {- (spec, RowFilterOutcome::TooLong)- }+ spec: &ScanSpec,+ upgrade: ColumnUpgrade,+ comment: ScanLogComment,+ lease_cancel: &CancellationToken,+ shutdown: &CancellationToken,+ ) -> Result<PropertiesSourcing, ScanHalt> {+ let sql = ambiguous_value_probe_sql(spec, upgrade.backed());+ // The column form's scan is longer than the probe, so it would not fit either.+ if !fits_client_get(&sql) {+ return Ok(PropertiesSourcing::Decided(upgrade.decline_too_long()));+ }+ let probe = self+ .client+ .query(&sql)+ .with_option(LOG_COMMENT_OPTION, comment.to_string())+ .fetch_optional::<u8>();+ let found = tokio::select! {+ biased;+ _ = shutdown.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::Shutdown)),+ _ = lease_cancel.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::LeaseLost)),+ found = probe => found.map_err(ScanError::Probe)?,};- let team = team_label(&self.allowlist, team_id);- counter!(SCAN_ROW_FILTER, "outcome" => outcome.as_str(), "team_id" => team).increment(1);- spec+ Ok(match found {+ Some(_) => PropertiesSourcing::Decided(upgrade.decline_ambiguous_value()),+ None => PropertiesSourcing::Upgradable(upgrade),+ })+ }++ /// A failed or timed-out lookup returns no columns, so the scan reads the blob.+ async fn lookup_columns(&self, keys: &BTreeSet<&str>) -> MaterializedColumns {+ match tokio::time::timeout(+ MATERIALIZED_LOOKUP_TIMEOUT,+ MaterializedColumns::lookup(&self.client, keys),+ )+ .await+ {+ Ok(Ok(columns)) => columns,+ Ok(Err(error)) => {+ warn!(error = ?error, "materialized column lookup failed; the scan reads the properties blob");+ MaterializedColumns::default()+ }+ Err(_) => {+ warn!("materialized column lookup timed out; the scan reads the properties blob");+ MaterializedColumns::default()+ }+ }}/// Publish what this chunk's scan narrowed to, so a team that stops projecting is visible/// before its scan cost is.- fn record_projection(&self, team_id: TeamId, projection: &ChunkProjection) {+ fn record_narrowing(&self, team_id: TeamId, narrowed: &NarrowedScan) {let team = team_label(&self.allowlist, team_id);+ let projection = narrowed.sourced.projection();counter!(CHUNKS_PROJECTED,"outcome" => projection.outcome(),"team_id" => team.clone(),).increment(1);+ counter!(+ SCAN_PROPERTIES_SOURCE,+ "source" => narrowed.sourced.outcome().as_str(),+ "team_id" => team.clone(),+ )+ .increment(1);+ counter!(+ SCAN_ROW_FILTER,+ "outcome" => narrowed.filtered.outcome.as_str(),+ "team_id" => team.clone(),+ )+ .increment(1);let ChunkProjection::Projected(plan) = projection else {return;};- for (blob, source) in [- ("properties", &plan.properties),- ("person_properties", &plan.person_properties),+ for (blob, keys) in [+ ("properties", plan.properties.key_count()),+ ("person_properties", plan.person_properties.key_count()),] {- record_projected_keys(blob, source, team.clone());+ if let Some(keys) = keys {+ histogram!(PROJECTION_KEYS, "blob" => blob, "team_id" => team.clone())+ .record(keys as f64);+ }}}}-/// A blob's kept-key count, where there is one. [`BlobSource::Full`] has none — see-/// [`PROJECTION_KEYS`].-fn record_projected_keys(blob: &'static str, source: &BlobSource, team: Arc<str>) {- let keys = match source {- BlobSource::Full => return,- BlobSource::Empty => 0,- BlobSource::Keys(keys) => keys.count(),+#[derive(Debug)]+struct NarrowedScan {+ sourced: SourcedProjection,+ filtered: FilteredSpec,+}++#[derive(Debug)]+struct FilteredSpec {+ spec: ScanSpec,+ outcome: RowFilterOutcome,+}++/// Columns take the GET budget before the row filter: they keep ClickHouse off every row's blob.+fn narrow_scan(+ spec: ScanSpec,+ sourcing: PropertiesSourcing,+ row_filter: &ScanRowFilter,+ columns: &MaterializedColumns,+) -> NarrowedScan {+ let sourced = match sourcing {+ PropertiesSourcing::Decided(sourced) => sourced,+ PropertiesSourcing::Upgradable(upgrade)+ if fits_client_get(&scan_sql(&spec, &upgrade.column_form())) =>+ {+ upgrade.accept()+ }+ PropertiesSourcing::Upgradable(upgrade) => upgrade.decline_too_long(),};- histogram!(PROJECTION_KEYS, "blob" => blob, "team_id" => team).record(keys as f64);+ let filtered = fit_row_filter(spec, row_filter, columns, sourced.projection());+ NarrowedScan { sourced, filtered }+}++/// Drops the filter when the query would be too long to send, since every attempt would fail.+fn fit_row_filter(+ spec: ScanSpec,+ row_filter: &ScanRowFilter,+ columns: &MaterializedColumns,+ projection: &ChunkProjection,+) -> FilteredSpec {+ if row_filter.is_empty() {+ return FilteredSpec {+ spec,+ outcome: RowFilterOutcome::None,+ };+ }+ let filtered = spec+ .clone()+ .with_row_filter(row_filter_sql(row_filter, columns));+ // Both renderings, because the shadow compare sends the wide one with the same filter.+ let fits = [projection, &ChunkProjection::FullColumns]+ .into_iter()+ .all(|projection| fits_client_get(&scan_sql(&filtered, projection)));+ if fits {+ FilteredSpec {+ spec: filtered,+ outcome: RowFilterOutcome::reading(row_filter, columns),+ }+ } else {+ FilteredSpec {+ spec,+ outcome: RowFilterOutcome::TooLong,+ }+ }+}++fn column_lookup_keys<'a>(+ projection: &'a ChunkProjection,+ exact: &ColumnExactKeys,+ row_filter: &'a ScanRowFilter,+) -> BTreeSet<&'a str> {+ row_filter+ .keys()+ .into_iter()+ .chain(+ projection+ .column_candidates(exact)+ .into_iter()+ .flat_map(ProjectedKeys::iter),+ )+ .collect()}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -435,6 +540,14 @@ enum RowFilterOutcome {}impl RowFilterOutcome {+ fn reading(row_filter: &ScanRowFilter, columns: &MaterializedColumns) -> Self {+ if columns.covers(row_filter.keys()) {+ Self::Materialized+ } else {+ Self::PropertiesBlob+ }+ }+const fn as_str(self) -> &'static str {match self {Self::None => "none",@@ -711,6 +824,8 @@ pub enum ScanError {Domain(#[from] ChunkDomainError),#[error("building ClickHouse scan cursor")]Query(#[source] clickhouse::error::Error),+ #[error("probing ClickHouse for ambiguous column values")]+ Probe(#[source] clickhouse::error::Error),#[error("streaming ClickHouse scan cursor")]Cursor(#[source] clickhouse::error::Error),#[error("aggregating ClickHouse scan row")]@@ -727,10 +842,11 @@ mod tests {use std::collections::BTreeSet;use std::num::NonZeroU32;+ use super::super::sql::MAX_GET_QUERY_BYTES;use super::*;use crate::domain::{- plan_days, Boundary, ClaimEpoch, ColumnPlan, ConditionHash, Lookback, PlanCaps,- ProjectedKeys, RunId, SChunkMs, ScalarColumn,+ plan_days, BandSpec, BlobSource, Boundary, ClaimEpoch, ColumnPlan, ConditionHash, Lookback,+ PlanCaps, PropertiesOutcome, PropertiesSource, RunId, SChunkMs, ScalarColumn,};const HASH: &str = "aaaaaaaaaaaaaaaa";@@ -857,6 +973,56 @@ mod tests {assert_eq!(tiles[0].count(), 1);}+ fn pageview_spec() -> ScanSpec {+ let ScanPlan::Scan(spec) = plan_scan(+ TeamId(2),+ &domain(),+ &EventNameSet::new(["$pageview".to_owned()]),+ BandSpec::new(0, 1).unwrap(),+ ) else {+ panic!("one event name on a one-day domain is a scan");+ };+ spec+ }++ fn key_names(count: usize) -> impl Iterator<Item = String> {+ (0..count).map(|index| format!("key_{index:02}"))+ }++ fn rebuilt(count: usize) -> ChunkProjection {+ ChunkProjection::Projected(ColumnPlan {+ uuid: ScalarColumn::Empty,+ elements_chain: ScalarColumn::Empty,+ properties: PropertiesSource::Blob(BlobSource::Keys(+ ProjectedKeys::new(key_names(count).collect()).expect("the counts are non-zero"),+ )),+ person_properties: BlobSource::Empty,+ })+ }++ /// `event == '$pageview' AND properties[key] == literal`.+ fn row_filter_on(key: &str, literal: &str) -> ScanRowFilter {+ use crate::domain::row_filter::test_catalog::{catalog, event_and_property, hash, Leaf};+ let leaves = [Leaf {+ cohort: 1,+ key: "$pageview",+ hash: HASH,+ body: event_and_property("$pageview", key, literal),+ }];+ let filters = catalog(&leaves);+ let conditions = [PinnedCondition {+ cohort_id: CohortId(1),+ hash: hash(HASH),+ event_name: "$pageview".to_owned(),+ lookback: Lookback::SlidingDays(7),+ }];+ ConditionAnalyses::build(&conditions, &filters).row_filter(+ &EventNameSet::new(["$pageview".to_owned()]),+ &filters,+ &ActiveConditions::new([hash(HASH)]),+ )+ }+/// The projection metrics are the only report of what a chunk narrowed to, and a dashboard/// reads them by label. This pins the three sampling rules the recorder applies, which no test/// over the projection types themselves can see: a full blob takes no key sample at all, an@@ -869,31 +1035,86 @@ mod tests {fn the_projection_metrics_report_each_blob_by_its_own_rule() {let scanner = ChunkScanner::new(ClickHouseClient::new(clickhouse::Client::default(), Default::default()),- TeamAllowlist::Only(std::collections::HashSet::from([2])),+ TeamAllowlist::Only(std::collections::HashSet::from([2, 3])),false,);+ let narrow = |projection: ChunkProjection,+ exact: &ColumnExactKeys,+ columns: &MaterializedColumns| {+ narrow_scan(+ pageview_spec(),+ projection.source_properties(exact, columns),+ &ScanRowFilter::default(),+ columns,+ )+ };+ let two_keys = ChunkProjection::Projected(ColumnPlan {+ uuid: ScalarColumn::Empty,+ elements_chain: ScalarColumn::Empty,+ properties: PropertiesSource::Blob(BlobSource::Keys(+ ProjectedKeys::new(BTreeSet::from([+ "plan".to_string(),+ "utm_source".to_string(),+ ]))+ .expect("two keys are not empty"),+ )),+ person_properties: BlobSource::Empty,+ });+ let url = ChunkProjection::Projected(ColumnPlan {+ uuid: ScalarColumn::Empty,+ elements_chain: ScalarColumn::Empty,+ properties: PropertiesSource::Blob(BlobSource::Keys(+ ProjectedKeys::new(BTreeSet::from(["$current_url".to_string()]))+ .expect("one key is not empty"),+ )),+ person_properties: BlobSource::Full,+ });+ let url_column: MaterializedColumns =+ [("$current_url", "mat_$current_url")].into_iter().collect();+ let none = MaterializedColumns::default();let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();let handle = recorder.handle();metrics::with_local_recorder(&recorder, || {- scanner.record_projection(+ scanner.record_narrowing(TeamId(2),- &ChunkProjection::Projected(ColumnPlan {- uuid: ScalarColumn::Empty,- elements_chain: ScalarColumn::Empty,- properties: BlobSource::Keys(- ProjectedKeys::new(BTreeSet::from([- "plan".to_string(),- "utm_source".to_string(),- ]))- .expect("two keys are not empty"),- ),- person_properties: BlobSource::Empty,- }),+ &narrow(two_keys, &ColumnExactKeys::default(), &none),+ );+ scanner.record_narrowing(+ TeamId(2),+ &narrow(+ ChunkProjection::FullColumns,+ &ColumnExactKeys::default(),+ &none,+ ),+ );+ scanner.record_narrowing(+ TeamId(3),+ &narrow(url, &ColumnExactKeys::exact(["$current_url"]), &url_column),);- scanner.record_projection(TeamId(2), &ChunkProjection::FullColumns);});let rendered = handle.render();+ for (team, source) in [(2, "rebuilt_inexact_key"), (2, "whole"), (3, "columns")] {+ assert!(+ rendered.contains(&format!(+ "{SCAN_PROPERTIES_SOURCE}{{source=\"{source}\",team_id=\"{team}\"}} 1"+ )),+ "team {team} did not count its chunk under {source}:\n{rendered}"+ );+ }+ assert!(+ rendered.contains(&format!(+ "{SCAN_ROW_FILTER}{{outcome=\"none\",team_id=\"2\"}} 2"+ )),+ "a chunk without a row filter was not counted:\n{rendered}"+ );+ assert!(+ rendered.contains(&format!(+ "{PROJECTION_KEYS}_sum{{blob=\"properties\",team_id=\"3\"}} 1"+ )),+ "a column-backed key was not counted as a read key:\n{rendered}"+ );+for outcome in ["projected", "full_columns"] {assert!(rendered.contains(&format!(@@ -1063,6 +1284,83 @@ mod tests {);}+ #[test]+ fn the_lookup_covers_row_filter_keys_and_projected_keys_that_can_all_be_columns() {+ let row_filter = row_filter_on("$feature_flag", "my-flag");+ let all_exact = ColumnExactKeys::exact(key_names(2));+ let one_exact = ColumnExactKeys::exact(key_names(1));+ for (projection, exact, expected) in [+ (+ rebuilt(2),+ &all_exact,+ &["$feature_flag", "key_00", "key_01"][..],+ ),+ (rebuilt(2), &one_exact, &["$feature_flag"][..]),+ (+ ChunkProjection::FullColumns,+ &all_exact,+ &["$feature_flag"][..],+ ),+ ] {+ assert_eq!(+ column_lookup_keys(&projection, exact, &row_filter),+ expected.iter().copied().collect::<BTreeSet<_>>(),+ "{projection:?}"+ );+ }+ }++ #[test]+ fn the_column_form_keeps_the_get_budget_and_the_row_filter_gives_way() {+ let spec = pageview_spec();+ let exact = ColumnExactKeys::exact(key_names(6));+ let columns: MaterializedColumns = key_names(6)+ .map(|key| (key.clone(), format!("mat_{key}")))+ .collect();+ let PropertiesSourcing::Upgradable(upgrade) =+ rebuilt(6).source_properties(&exact, &columns)+ else {+ panic!("six exact keys with columns can be read from columns");+ };+ let column_form = upgrade.column_form();+ let filter_fits_beside = |projection: &ChunkProjection, literal_len: usize| {+ let row_filter = row_filter_on("key_00", &"x".repeat(literal_len));+ fit_row_filter(spec.clone(), &row_filter, &columns, projection).outcome+ != RowFilterOutcome::TooLong+ };+ // The longest filter that still fits beside the rebuild.+ let lengths = (0..MAX_GET_QUERY_BYTES).collect::<Vec<_>>();+ let literal_len = lengths+ .partition_point(|len| filter_fits_beside(&rebuilt(6), *len))+ .checked_sub(1)+ .expect("even an empty filter literal does not fit beside the rebuild");+ assert!(+ !filter_fits_beside(&column_form, literal_len),+ "the column form is no longer longer than the rebuild, so nothing competes"+ );++ let near_the_limit = narrow_scan(+ spec.clone(),+ rebuilt(6).source_properties(&exact, &columns),+ &row_filter_on("key_00", &"x".repeat(literal_len)),+ &columns,+ );+ assert_eq!(near_the_limit.sourced.outcome(), PropertiesOutcome::Columns);+ assert_eq!(near_the_limit.sourced.projection(), &column_form);+ assert_eq!(near_the_limit.filtered.outcome, RowFilterOutcome::TooLong);+ assert_eq!(near_the_limit.filtered.spec, spec);++ let short = narrow_scan(+ spec.clone(),+ rebuilt(6).source_properties(&exact, &columns),+ &row_filter_on("key_00", "x"),+ &columns,+ );+ assert_eq!(short.sourced.outcome(), PropertiesOutcome::Columns);+ assert_eq!(short.filtered.outcome, RowFilterOutcome::Materialized);+ assert_ne!(short.filtered.spec, spec, "the row filter was dropped");+ }+#[test]fn scan_time_rechecks_sliding_conditions_against_the_current_day() {let hash = ConditionHash::parse(HASH).unwrap();diff --git a/rust/cohort-seeder/src/clickhouse/sql.rs b/rust/cohort-seeder/src/clickhouse/sql.rsindex fe2c39573249..4b418dc4e4de 100644--- a/rust/cohort-seeder/src/clickhouse/sql.rs+++ b/rust/cohort-seeder/src/clickhouse/sql.rs@@ -7,10 +7,9 @@ use std::num::NonZeroU32;use cohort_core::filters::TeamId;use cohort_core::hogvm::analysis::PropertyAlternatives;-use super::materialized::MaterializedColumns;use crate::domain::{- BandSpec, BlobSource, ChunkProjection, ColumnPlan, EventNameSet, ProjectedKeys, ScalarColumn,- ScanRowFilter, SeedDomain,+ BandSpec, BlobSource, ChunkProjection, ColumnBackedKeys, ColumnName, ColumnPlan, EventNameSet,+ MaterializedColumns, ProjectedKeys, PropertiesSource, ScalarColumn, ScanRowFilter, SeedDomain,};/// The crate sends a longer query by POST with `readonly=1`, which the `cohort_seeder` profile's@@ -97,12 +96,6 @@ pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {ChunkProjection::FullColumns => render_select_list(&ColumnPlan::full()),ChunkProjection::Projected(plan) => render_select_list(plan),};- let event_names = spec- .event_names- .iter()- .map(|name| clickhouse_string_literal(name))- .collect::<Vec<_>>()- .join(", ");let row_filter = spec.row_filter.as_ref()@@ -118,19 +111,52 @@ pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {};format!(- "SELECT {}\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = {}\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = {}\n AND e.timestamp >= fromUnixTimestamp64Milli({})\n AND e.timestamp < fromUnixTimestamp64Milli({})\n AND e.event IN ({})\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli({}){}{}",+ "SELECT {}\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = {}\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE {}{}{}",select_list,spec.team_id.0,- spec.team_id.0,- spec.day_start_ms,- spec.day_end_ms,- event_names,- spec.s_chunk_ms,+ chunk_rows_sql(spec),row_filter,band_predicate,)}+/// Finds a row of the chunk where a column the scan would read cannot tell the boolean `false` from+/// the string `"false"`. It leaves out only the row filter and the band, so it reads every row the+/// scan can read.+pub fn ambiguous_value_probe_sql(spec: &ScanSpec, columns: &ColumnBackedKeys) -> String {+ format!(+ "SELECT 1\nFROM events AS e\nWHERE {}\n AND {}\nLIMIT 1",+ chunk_rows_sql(spec),+ ambiguous_values_sql(columns),+ )+}++/// True where [`columns_object_expr`] would build the boolean `false`. A string keeps its spaces in+/// the column, and JSON reads ` false ` as the boolean. Tabs and line breaks stay escaped.+pub fn ambiguous_values_sql(columns: &ColumnBackedKeys) -> String {+ join_terms(+ columns.iter().map(|(_, column)| {+ format!("trim(BOTH ' ' FROM {}) = 'false'", column_reference(column))+ }),+ "OR",+ )+}++/// One team, one day, the chunk's event names, and only rows inserted before the chunk's claim.+/// The claim is in the past, so every query over the chunk reads the same rows.+fn chunk_rows_sql(spec: &ScanSpec) -> String {+ let event_names = spec+ .event_names+ .iter()+ .map(|name| clickhouse_string_literal(name))+ .collect::<Vec<_>>()+ .join(", ");+ format!(+ "e.team_id = {}\n AND e.timestamp >= fromUnixTimestamp64Milli({})\n AND e.timestamp < fromUnixTimestamp64Milli({})\n AND e.event IN ({})\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli({})",+ spec.team_id.0, spec.day_start_ms, spec.day_end_ms, event_names, spec.s_chunk_ms,+ )+}+/// Renders a superset of HogVM equality (see [`cohort_core::hogvm::analysis::EventRowFilter`]) over/// the value's raw JSON text without its outer quotes. The string `value` reads as itself, or holds a/// backslash when JSON escapes one of its characters; a boolean reads as `true` or `false`; an object@@ -197,7 +223,7 @@ fn property_value_sql<'a>(// past 64 bits, which `serde_json` reads. A materialized column stores that '', so admitting ''// there keeps the test off the blob.let (value, unparsed) = match columns.column_for(key) {- Some(column) => (format!("e.{}", clickhouse_identifier(column)), "v = ''"),+ Some(column) => (column_reference(column), "v = ''"),None => (format!("replaceRegexpAll(JSONExtractRaw(e.properties, {}), '^\"|\"$', '')",@@ -229,6 +255,10 @@ fn join_terms(terms: impl Iterator<Item = String>, operator: &str) -> String {}}+fn column_reference(column: &ColumnName) -> String {+ format!("e.{}", clickhouse_identifier(column.as_str()))+}+/// Escaped for the server and for the client's template parser, which reads a bare `?` as a bind.fn clickhouse_identifier(name: &str) -> String {let mut escaped = String::with_capacity(name.len() + 2);@@ -255,7 +285,7 @@ fn render_select_list(plan: &ColumnPlan) -> String {ScalarColumn::Keep => "toString(e.uuid) AS uuid".to_string(),ScalarColumn::Empty => "'' AS uuid".to_string(),},- render_blob("e.properties", "properties", &plan.properties),+ render_properties(&plan.properties),render_blob("e.person_properties","person_properties",@@ -268,6 +298,15 @@ fn render_select_list(plan: &ColumnPlan) -> String {)}+fn render_properties(source: &PropertiesSource) -> String {+ match source {+ PropertiesSource::Blob(blob) => render_blob("e.properties", "properties", blob),+ PropertiesSource::Columns(columns) => {+ format!("{} AS properties", columns_object_expr(columns))+ }+ }+}+/// A JSON blob column, selected whole, replaced by an empty literal, or rebuilt from the keys the/// chunk reads. An empty literal is what the row decoder lifts to "absent", which the globals/// builder reads as `{}` without parsing anything.@@ -315,6 +354,23 @@ pub fn rebuild_expr(column: &str, keys: &ProjectedKeys) -> String {)}+/// A trim-quotes column drops a string's quotes, so text that is not valid JSON gets them back.+pub fn columns_object_expr(columns: &ColumnBackedKeys) -> String {+ let entries = columns+ .iter()+ .map(|(key, column)| {+ let name = serde_json::to_string(key).expect("a string always serializes to JSON");+ let value = column_reference(column);+ format!(+ "{}, if(isValidJSON({value}), {value}, concat('\"', {value}, '\"'))",+ clickhouse_string_literal(&format!("{name}:")),+ )+ })+ .collect::<Vec<_>>()+ .join(", ',', ");+ format!("concat('{{', {entries}, '}}')")+}+/// `keys` as a comma-separated list of string literals, for an `IN (...)` or an array literal.pub(crate) fn key_list(keys: &ProjectedKeys) -> String {keys.iter()@@ -364,7 +420,7 @@ mod tests {use chrono_tz::UTC;use super::*;- use crate::domain::{SChunkMs, SeedDomain};+ use crate::domain::{ColumnExactKeys, SChunkMs, SeedDomain};/// The rendered scan for a spec, wide.fn full_sql(spec: &ScanSpec) -> String {@@ -472,7 +528,7 @@ mod tests {let projection = ChunkProjection::Projected(ColumnPlan {uuid: ScalarColumn::Empty,elements_chain: ScalarColumn::Empty,- properties: BlobSource::Empty,+ properties: PropertiesSource::Blob(BlobSource::Empty),person_properties: BlobSource::Empty,});assert_eq!(@@ -488,7 +544,7 @@ mod tests {let projection = ChunkProjection::Projected(ColumnPlan {uuid: ScalarColumn::Keep,elements_chain: ScalarColumn::Empty,- properties: BlobSource::Keys(keys(&["plan", "utm_source"])),+ properties: PropertiesSource::Blob(BlobSource::Keys(keys(&["plan", "utm_source"]))),person_properties: BlobSource::Full,});assert_eq!(@@ -505,7 +561,7 @@ mod tests {let projection = ChunkProjection::Projected(ColumnPlan {uuid: ScalarColumn::Keep,elements_chain: ScalarColumn::Empty,- properties: BlobSource::Full,+ properties: PropertiesSource::Blob(BlobSource::Full),person_properties: BlobSource::Keys(keys(&["email", "plan"])),});assert_eq!(@@ -523,12 +579,12 @@ mod tests {let projection = ChunkProjection::Projected(ColumnPlan {uuid: ScalarColumn::Empty,elements_chain: ScalarColumn::Keep,- properties: BlobSource::Keys(keys(&[+ properties: PropertiesSource::Blob(BlobSource::Keys(keys(&["quote' OR 1 = 1 --","slash\\key\nnext","converted?","$feature/flag",- ])),+ ]))),person_properties: BlobSource::Empty,});let sql = scan_sql(&unbanded_spec(), &projection);@@ -546,6 +602,46 @@ mod tests {assert!(select_list_of(&sql).ends_with("e.elements_chain"), "{sql}");}+ fn backed(pairs: &[(&'static str, &'static str)]) -> ColumnBackedKeys {+ let names = pairs.iter().map(|(key, _)| *key).collect::<Vec<_>>();+ ColumnExactKeys::exact(names.iter().copied())+ .back(&keys(&names), &pairs.iter().copied().collect())+ .expect("every test key is exact and has a column")+ }++ #[test]+ fn column_backed_properties_read_each_key_from_its_column() {+ let columns = backed(&[+ ("$current_url", "mat_$current_url"),+ ("$pathname", "mat_$pathname"),+ ]);+ assert_eq!(+ ambiguous_value_probe_sql(&unbanded_spec(), &columns),+ "SELECT 1\nFROM events AS e\nWHERE e.team_id = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('purchase')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)\n AND (trim(BOTH ' ' FROM e.`mat_$current_url`) = 'false' OR trim(BOTH ' ' FROM e.`mat_$pathname`) = 'false')\nLIMIT 1"+ );+ let projection = ChunkProjection::Projected(ColumnPlan {+ uuid: ScalarColumn::Empty,+ elements_chain: ScalarColumn::Empty,+ properties: PropertiesSource::Columns(columns),+ person_properties: BlobSource::Empty,+ });+ let sql = scan_sql(&unbanded_spec(), &projection);+ assert_eq!(+ select_list_of(&sql),+ "'' AS uuid, e.event, concat('{', '\"$current_url\":', if(isValidJSON(e.`mat_$current_url`), e.`mat_$current_url`, concat('\"', e.`mat_$current_url`, '\"')), ',', '\"$pathname\":', if(isValidJSON(e.`mat_$pathname`), e.`mat_$pathname`, concat('\"', e.`mat_$pathname`, '\"')), '}') AS properties, toString(e.timestamp) AS timestamp,\n e.distinct_id,\n toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)) AS person_id,\n '' AS person_properties, '' AS elements_chain"+ );+ assert!(!sql.contains("e.properties"), "{sql}");+ }++ #[test]+ fn column_backed_keys_and_columns_are_escaped_for_json_and_for_sql() {+ let rendered = columns_object_expr(&backed(&[("q'\"\\?", "mat_`q?")]));+ assert_eq!(+ rendered,+ r#"concat('{', '"q\'\\"\\\\??":', if(isValidJSON(e.`mat_\`q??`), e.`mat_\`q??`, concat('"', e.`mat_\`q??`, '"')), '}')"#+ );+ }+#[test]fn the_row_filter_passes_other_events_and_reads_materialized_columns() {use crate::domain::row_filter::test_catalog::{catalog, event_and_property, hash, Leaf};diff --git a/rust/cohort-seeder/src/domain/columns.rs b/rust/cohort-seeder/src/domain/columns.rsnew file mode 100644index 000000000000..4e226492d523--- /dev/null+++ b/rust/cohort-seeder/src/domain/columns.rs@@ -0,0 +1,49 @@+//! Domain layer: materialized columns verified to hold a `properties` key's trim-quotes value.++use std::collections::HashMap;++#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct ColumnName(String);++impl ColumnName {+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++impl From<String> for ColumnName {+ fn from(name: String) -> Self {+ Self(name)+ }+}++impl From<&str> for ColumnName {+ fn from(name: &str) -> Self {+ Self(name.to_owned())+ }+}++/// Property key to verified column name.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct MaterializedColumns(HashMap<String, ColumnName>);++impl MaterializedColumns {+ pub fn column_for(&self, key: &str) -> Option<&ColumnName> {+ self.0.get(key)+ }++ pub fn covers<'k>(&self, keys: impl IntoIterator<Item = &'k str>) -> bool {+ keys.into_iter().all(|key| self.0.contains_key(key))+ }+}++/// The first column given for a key wins.+impl<K: Into<String>, C: Into<ColumnName>> FromIterator<(K, C)> for MaterializedColumns {+ fn from_iter<I: IntoIterator<Item = (K, C)>>(pairs: I) -> Self {+ let mut columns = HashMap::new();+ for (key, column) in pairs {+ columns.entry(key.into()).or_insert_with(|| column.into());+ }+ Self(columns)+ }+}diff --git a/rust/cohort-seeder/src/domain/condition_analysis.rs b/rust/cohort-seeder/src/domain/condition_analysis.rsindex 652d6204e085..8734050a154f 100644--- a/rust/cohort-seeder/src/domain/condition_analysis.rs+++ b/rust/cohort-seeder/src/domain/condition_analysis.rs@@ -22,14 +22,15 @@ use std::sync::Arc;use cohort_core::filters::TeamFilters;use cohort_core::hogvm::analysis::{- analyze_condition_within, event_row_filter, AnalysisBudget, ConditionAnalysis, EvaluationClass,- EventRowFilter, FullColumnsReason, Projection, ReadPath,+ analyze_condition_within, event_equalities, AnalysisBudget, ColumnExactness, ConditionAnalysis,+ EvaluationClass, EventEqualities, Exactness, FullColumnsReason, GlobalRoot, Projection,+ ReadPath,};use super::condition::{EventNameSet, PinnedCondition};use super::ids::ConditionHash;use super::plan::ActiveConditions;-use super::projection::ChunkProjection;+use super::projection::{ChunkProjection, ColumnExactKeys};use super::row_filter::ScanRowFilter;/// What one condition turned out to need. Ordered so a census renders the same way every time.@@ -120,7 +121,7 @@ const CENSUS_WORST_CASE_CONDITIONS: usize = 8;pub struct ConditionAnalyses {by_hash: HashMap<ConditionHash, ConditionAnalysis>,/// Not budgeted, because matching is linear in the program.- row_filters: HashMap<ConditionHash, EventRowFilter>,+ equalities: HashMap<ConditionHash, EventEqualities>,}impl ConditionAnalyses {@@ -132,7 +133,7 @@ impl ConditionAnalyses {pub fn build(conditions: &[PinnedCondition], filters: &TeamFilters) -> Self {let mut budget = AnalysisBudget::for_conditions(CENSUS_WORST_CASE_CONDITIONS);let mut by_hash = HashMap::new();- let mut row_filters = HashMap::new();+ let mut equalities = HashMap::new();for condition in conditions {if by_hash.contains_key(&condition.hash) {continue;@@ -147,13 +148,11 @@ impl ConditionAnalyses {condition.hash,analyze_condition_within(program.tokens(), &mut budget),);- if let Some(row_filter) = event_row_filter(program.tokens()) {- row_filters.insert(condition.hash, row_filter);- }+ equalities.insert(condition.hash, event_equalities(program.tokens()));}Self {by_hash,- row_filters,+ equalities,}}@@ -163,11 +162,46 @@ impl ConditionAnalyses {filters: &TeamFilters,active: &ActiveConditions,) -> ScanRowFilter {- ScanRowFilter::derive(event_names, filters, active, &self.row_filters)+ ScanRowFilter::derive(event_names, filters, active, &self.equalities)}pub fn row_filtered_conditions(&self) -> usize {- self.row_filters.len()+ self.equalities+ .values()+ .filter(|equalities| equalities.row_filter.is_some())+ .count()+ }++ /// One inexact read by any active condition keeps a key on the blob.+ pub fn column_exact_keys(&self, active: &ActiveConditions) -> ColumnExactKeys {+ active+ .iter()+ .map(|hash| self.column_exactness(hash))+ .collect::<Option<ColumnExactness>>()+ .map(ColumnExactKeys::new)+ .unwrap_or_default()+ }++ /// `None` when the condition's reads are unknown.+ fn column_exactness(&self, hash: &ConditionHash) -> Option<ColumnExactness> {+ let Projection::Reads(paths) = &self.by_hash.get(hash)?.projection else {+ return None;+ };+ let decided = self+ .equalities+ .get(hash)+ .and_then(|equalities| equalities.column_exactness.as_ref());+ paths+ .iter()+ .filter(|path| path.root == GlobalRoot::Properties)+ .map(|path| {+ let key = path.segments.first()?;+ let exactness = decided+ .and_then(|keys| keys.get(key))+ .unwrap_or(Exactness::Inexact);+ Some((key.as_str(), exactness))+ })+ .collect()}/// What a scan over the conditions active on one chunk has to select.@@ -423,7 +457,7 @@ mod tests {use serde_json::json;use super::*;- use crate::domain::{BlobSource, Lookback};+ use crate::domain::{BlobSource, Lookback, PropertiesSource};fn hash(value: &str) -> ConditionHash {ConditionHash::parse(value).expect("test hashes are 16 ASCII bytes")@@ -495,6 +529,32 @@ mod tests {])}+ /// `properties.<key> == <literal> AND event == 'purchase'`.+ fn property_equality(key: &str, literal: &str) -> serde_json::Value {+ json!([+ "_H",+ 1,+ 32,+ literal,+ 32,+ key,+ 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])@@ -747,7 +807,9 @@ mod tests {panic!("the narrow condition alone must project");};match &plan.properties {- BlobSource::Keys(keys) => assert_eq!(keys.iter().collect::<Vec<_>>(), ["plan"]),+ PropertiesSource::Blob(BlobSource::Keys(keys)) => {+ assert_eq!(keys.iter().collect::<Vec<_>>(), ["plan"]);+ }other => panic!("expected key-filtered properties, got {other:?}"),}@@ -755,6 +817,60 @@ mod tests {assert_eq!(analyses.projection(&both), ChunkProjection::FullColumns);}+ #[test]+ fn a_key_is_column_exact_only_when_every_active_condition_reading_it_is() {+ let conditions = [+ condition("exactplan0000000", "purchase"),+ condition("inexactplan00000", "purchase"),+ condition("exacturl00000000", "purchase"),+ condition("wide000000000000", "checkout"),+ ];+ let catalog = filters(&[+ (+ "exactplan0000000",+ "purchase",+ property_equality("plan", "paid"),+ ),+ (+ "inexactplan00000",+ "purchase",+ property_equality("plan", "TRUE"),+ ),+ (+ "exacturl00000000",+ "purchase",+ property_equality("$current_url", "https://example.com/"),+ ),+ ("wide000000000000", "checkout", bare_properties()),+ ]);+ let analyses = ConditionAnalyses::build(&conditions, &catalog);+ let exact_on = |active: &[&str]| {+ analyses.column_exact_keys(&ActiveConditions::new(+ active.iter().map(|value| hash(value)),+ ))+ };+ let exact_keys = |active: &[&str]| {+ exact_on(active)+ .exact_keys()+ .map(str::to_owned)+ .collect::<Vec<_>>()+ };++ assert_eq!(+ exact_keys(&["exactplan0000000", "inexactplan00000", "exacturl00000000"]),+ ["$current_url"]+ );+ assert_eq!(+ exact_keys(&["exactplan0000000", "exacturl00000000"]),+ ["$current_url", "plan"]+ );+ assert_eq!(+ exact_keys(&["exacturl00000000", "wide000000000000"]),+ Vec::<String>::new(),+ "a condition reading the whole object keeps every key on the blob"+ );+ }+/// An active hash the frozen catalog carried no bytecode for never reached the analyzer, so its/// reads are unknown and the chunk has to take every column.#[test]diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rsindex bb923f502709..0416aa312eeb 100644--- a/rust/cohort-seeder/src/domain/mod.rs+++ b/rust/cohort-seeder/src/domain/mod.rs@@ -11,6 +11,7 @@pub mod aggregate;pub mod backoff;pub mod chunk;+pub mod columns;pub mod compare;pub mod completion;pub mod condition;@@ -40,6 +41,7 @@ pub use cohort_core::seed::{BehavioralShapeHash, PersonSeed, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope,ReconcileTile, ScopeKind, SeedTile, ShapeHashError, UnknownScopeKind,};+pub use columns::{ColumnName, MaterializedColumns};pub use compare::{diff_tiles, Divergence, DivergenceClass, TileDiff, MAX_EXEMPLARS_PER_CLASS};pub(crate) use completion::MARKER_WATCH_SCHEMA;pub use completion::{@@ -73,6 +75,10 @@ pub use pinned::{UncoveredReason, UnknownTriggerKind, ValidatedPinnedRun,};pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};-pub use projection::{BlobSource, ChunkProjection, ColumnPlan, ProjectedKeys, ScalarColumn};+pub use projection::{+ BlobSource, ChunkProjection, ColumnBackedKeys, ColumnExactKeys, ColumnPlan, ColumnUpgrade,+ ProjectedKeys, PropertiesOutcome, PropertiesSource, PropertiesSourcing, RebuildReason,+ ScalarColumn, SourcedProjection, Unbacked,+};pub use row_filter::{ConditionConjuncts, ScanRowFilter};pub use window::{Boundary, DaySchedule, DomainError, PlanCaps, PlannedDay, SeedDomain};diff --git a/rust/cohort-seeder/src/domain/projection.rs b/rust/cohort-seeder/src/domain/projection.rsindex 83c08a248c8e..a9abc1447dd4 100644--- a/rust/cohort-seeder/src/domain/projection.rs+++ b/rust/cohort-seeder/src/domain/projection.rs@@ -19,9 +19,13 @@//! timestamp to place the row in its day, the accumulator keys on the person, and the event name//! selects which conditions run. Leaving them out of [`ColumnPlan`] means no caller can ask for that.-use std::collections::BTreeSet;+use std::collections::{BTreeMap, BTreeSet};-use cohort_core::hogvm::analysis::{ConditionAnalysis, GlobalRoot, Projection, ReadPath};+use cohort_core::hogvm::analysis::{+ ColumnExactness, ConditionAnalysis, Exactness, GlobalRoot, Projection, ReadPath,+};++use super::columns::{ColumnName, MaterializedColumns};/// What one chunk's scan must select.#[derive(Debug, Clone, PartialEq, Eq)]@@ -36,7 +40,7 @@ pub enum ChunkProjection {pub struct ColumnPlan {pub uuid: ScalarColumn,pub elements_chain: ScalarColumn,- pub properties: BlobSource,+ pub properties: PropertiesSource,pub person_properties: BlobSource,}@@ -58,6 +62,13 @@ pub enum BlobSource {Keys(ProjectedKeys),}+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PropertiesSource {+ Blob(BlobSource),+ /// Only the event's own properties have materialized columns.+ Columns(ColumnBackedKeys),+}+/// A non-empty set of top-level keys, in a stable order so a rendered scan is reproducible.////// Non-empty by construction: an empty key set would render `{}`, which [`BlobSource::Empty`]@@ -83,6 +94,194 @@ impl ProjectedKeys {}}+/// Non-empty, and built only from keys proven exact.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ColumnBackedKeys(BTreeMap<String, ColumnName>);++impl ColumnBackedKeys {+ pub fn iter(&self) -> impl ExactSizeIterator<Item = (&str, &ColumnName)> {+ self.0.iter().map(|(key, column)| (key.as_str(), column))+ }++ pub fn count(&self) -> usize {+ self.0.len()+ }+}++/// Keys every active condition reads only through exact equalities.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ColumnExactKeys(ColumnExactness);++impl ColumnExactKeys {+ /// Only the condition analysis may build one.+ pub(crate) fn new(exactness: ColumnExactness) -> Self {+ Self(exactness)+ }++ #[cfg(test)]+ pub(crate) fn exact<K: Into<String>>(keys: impl IntoIterator<Item = K>) -> Self {+ Self(+ keys.into_iter()+ .map(|key| (key, Exactness::Exact))+ .collect(),+ )+ }++ #[cfg(test)]+ pub(crate) fn exact_keys(&self) -> impl Iterator<Item = &str> {+ self.0.exact_keys()+ }++ fn covers(&self, keys: &ProjectedKeys) -> bool {+ keys.iter()+ .all(|key| self.0.get(key) == Some(Exactness::Exact))+ }++ pub(crate) fn back(+ &self,+ keys: &ProjectedKeys,+ columns: &MaterializedColumns,+ ) -> Result<ColumnBackedKeys, Unbacked> {+ if !self.covers(keys) {+ return Err(Unbacked::InexactKey);+ }+ keys.iter()+ .map(|key| Some((key.to_owned(), columns.column_for(key)?.clone())))+ .collect::<Option<_>>()+ .map(ColumnBackedKeys)+ .ok_or(Unbacked::NoColumn)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Unbacked {+ InexactKey,+ /// A key has no column, or the lookup failed.+ NoColumn,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RebuildReason {+ Unbacked(Unbacked),+ TooLong,+ /// A column of the chunk holds a value that reads as `false`. It can be the boolean or the+ /// string `"false"`, and the VM answers an exact equality on the two oppositely.+ AmbiguousValue,+}++/// The `source` label of `seeder_scan_properties_source_total`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PropertiesOutcome {+ Whole,+ Empty,+ Columns,+ Rebuilt(RebuildReason),+}++impl PropertiesOutcome {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Whole => "whole",+ Self::Empty => "empty",+ Self::Columns => "columns",+ Self::Rebuilt(RebuildReason::Unbacked(Unbacked::InexactKey)) => "rebuilt_inexact_key",+ Self::Rebuilt(RebuildReason::Unbacked(Unbacked::NoColumn)) => "rebuilt_no_column",+ Self::Rebuilt(RebuildReason::TooLong) => "rebuilt_too_long",+ Self::Rebuilt(RebuildReason::AmbiguousValue) => "rebuilt_ambiguous_value",+ }+ }+}++#[derive(Debug)]+pub enum PropertiesSourcing {+ Decided(SourcedProjection),+ /// The caller decides whether the column form fits and whether the chunk's values are+ /// unambiguous.+ Upgradable(ColumnUpgrade),+}++#[derive(Debug)]+pub struct ColumnUpgrade {+ rebuilt: ColumnPlan,+ backed: ColumnBackedKeys,+}++impl ColumnUpgrade {+ pub fn backed(&self) -> &ColumnBackedKeys {+ &self.backed+ }++ pub fn column_form(&self) -> ChunkProjection {+ ChunkProjection::Projected(ColumnPlan {+ properties: PropertiesSource::Columns(self.backed.clone()),+ ..self.rebuilt.clone()+ })+ }++ pub fn accept(self) -> SourcedProjection {+ SourcedProjection {+ projection: self.column_form(),+ outcome: PropertiesOutcome::Columns,+ }+ }++ pub fn decline_too_long(self) -> SourcedProjection {+ self.decline(RebuildReason::TooLong)+ }++ pub fn decline_ambiguous_value(self) -> SourcedProjection {+ self.decline(RebuildReason::AmbiguousValue)+ }++ fn decline(self, reason: RebuildReason) -> SourcedProjection {+ SourcedProjection {+ projection: ChunkProjection::Projected(self.rebuilt),+ outcome: PropertiesOutcome::Rebuilt(reason),+ }+ }+}++/// Built only by sourcing, so the projection and its label agree.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SourcedProjection {+ projection: ChunkProjection,+ outcome: PropertiesOutcome,+}++impl SourcedProjection {+ pub fn projection(&self) -> &ChunkProjection {+ &self.projection+ }++ pub const fn outcome(&self) -> PropertiesOutcome {+ self.outcome+ }++ pub fn into_projection(self) -> ChunkProjection {+ self.projection+ }+}++impl BlobSource {+ /// `None` when the scan reads the whole blob.+ pub fn key_count(&self) -> Option<usize> {+ match self {+ Self::Full => None,+ Self::Empty => Some(0),+ Self::Keys(keys) => Some(keys.count()),+ }+ }+}++impl PropertiesSource {+ pub fn key_count(&self) -> Option<usize> {+ match self {+ Self::Blob(blob) => blob.key_count(),+ Self::Columns(columns) => Some(columns.count()),+ }+ }+}+impl ColumnPlan {/// Every narrowable column selected whole — what the seeder scanned before this existed.///@@ -93,7 +292,7 @@ impl ColumnPlan {Self {uuid: ScalarColumn::Keep,elements_chain: ScalarColumn::Keep,- properties: BlobSource::Full,+ properties: PropertiesSource::Blob(BlobSource::Full),person_properties: BlobSource::Full,}}@@ -124,6 +323,50 @@ impl ChunkProjection {Self::Projected(demand.into_plan())}+ /// All projected keys when all are exact; one key left on the blob reads the whole blob.+ pub fn column_candidates(&self, exact: &ColumnExactKeys) -> Option<&ProjectedKeys> {+ let Self::Projected(plan) = self else {+ return None;+ };+ match &plan.properties {+ PropertiesSource::Blob(BlobSource::Keys(keys)) => exact.covers(keys).then_some(keys),+ PropertiesSource::Blob(BlobSource::Full | BlobSource::Empty)+ | PropertiesSource::Columns(_) => None,+ }+ }++ /// Never upgrades [`ChunkProjection::FullColumns`], which the shadow compare's wide arm needs.+ pub fn source_properties(+ self,+ exact: &ColumnExactKeys,+ columns: &MaterializedColumns,+ ) -> PropertiesSourcing {+ let Self::Projected(plan) = self else {+ return PropertiesSourcing::Decided(SourcedProjection {+ projection: self,+ outcome: PropertiesOutcome::Whole,+ });+ };+ let outcome = match &plan.properties {+ PropertiesSource::Columns(_) => PropertiesOutcome::Columns,+ PropertiesSource::Blob(BlobSource::Full) => PropertiesOutcome::Whole,+ PropertiesSource::Blob(BlobSource::Empty) => PropertiesOutcome::Empty,+ PropertiesSource::Blob(BlobSource::Keys(keys)) => match exact.back(keys, columns) {+ Ok(backed) => {+ return PropertiesSourcing::Upgradable(ColumnUpgrade {+ rebuilt: plan,+ backed,+ })+ }+ Err(unbacked) => PropertiesOutcome::Rebuilt(RebuildReason::Unbacked(unbacked)),+ },+ };+ PropertiesSourcing::Decided(SourcedProjection {+ projection: Self::Projected(plan),+ outcome,+ })+ }+/// The label this chunk's scan is metered under.pub const fn outcome(&self) -> &'static str {match self {@@ -242,7 +485,7 @@ impl Demand {ColumnPlan {uuid: keep_if(self.uuid),elements_chain: keep_if(self.elements_chain),- properties: self.properties.freeze(),+ properties: PropertiesSource::Blob(self.properties.freeze()),person_properties: self.person_properties.freeze(),}}@@ -292,6 +535,13 @@ mod tests {}}+ fn blob(source: &PropertiesSource) -> &BlobSource {+ match source {+ PropertiesSource::Blob(blob) => blob,+ PropertiesSource::Columns(columns) => panic!("expected the blob, got {columns:?}"),+ }+ }+fn keys(source: &BlobSource) -> Vec<&str> {match source {BlobSource::Keys(keys) => keys.iter().collect(),@@ -318,7 +568,7 @@ mod tests {ColumnPlan {uuid: ScalarColumn::Empty,elements_chain: ScalarColumn::Empty,- properties: BlobSource::Empty,+ properties: PropertiesSource::Blob(BlobSource::Empty),person_properties: BlobSource::Empty,});@@ -339,7 +589,7 @@ mod tests {path(GlobalRoot::ElementsChainIds, &[]),path(GlobalRoot::ElementsChainElements, &[]),])]);- assert_eq!(plan.properties, BlobSource::Empty);+ assert_eq!(plan.properties, PropertiesSource::Blob(BlobSource::Empty));assert_eq!(plan.person_properties, BlobSource::Empty);assert_eq!(plan.uuid, ScalarColumn::Empty);assert_eq!(plan.elements_chain, ScalarColumn::Empty);@@ -354,7 +604,7 @@ mod tests {path(GlobalRoot::Person, &["properties", "company", "size"]),path(GlobalRoot::Pdi, &["person", "properties", "email"]),])]);- assert_eq!(keys(&plan.properties), ["$set"]);+ assert_eq!(keys(blob(&plan.properties)), ["$set"]);assert_eq!(keys(&plan.person_properties), ["company", "email"]);}@@ -366,7 +616,7 @@ mod tests {reads([path(GlobalRoot::Properties, &["utm_source"])]),reads([path(GlobalRoot::Properties, &["plan"])]),]);- assert_eq!(keys(&plan.properties), ["plan", "utm_source"]);+ assert_eq!(keys(blob(&plan.properties)), ["plan", "utm_source"]);}/// `person.properties` and `pdi.person` name whole objects whose keys are chosen at runtime, so@@ -383,7 +633,11 @@ mod tests {]);assert_eq!(plan.person_properties, BlobSource::Full, "{whole:?}");// Only the person blob widens: the event's own properties are untouched by it.- assert_eq!(plan.properties, BlobSource::Empty, "{whole:?}");+ assert_eq!(+ plan.properties,+ PropertiesSource::Blob(BlobSource::Empty),+ "{whole:?}"+ );}}@@ -417,7 +671,7 @@ mod tests {path(GlobalRoot::Properties, &["$elements_chain"]),])]);assert_eq!(plan.elements_chain, ScalarColumn::Keep);- assert_eq!(keys(&plan.properties), ["$elements_chain"]);+ assert_eq!(keys(blob(&plan.properties)), ["$elements_chain"]);}/// Every way a condition can escape the analysis takes the whole chunk wide, whatever its@@ -452,12 +706,115 @@ mod tests {ChunkProjection::Projected(ColumnPlan {uuid: ScalarColumn::Empty,elements_chain: ScalarColumn::Empty,- properties: BlobSource::Empty,+ properties: PropertiesSource::Blob(BlobSource::Empty),person_properties: BlobSource::Empty,}));}+ fn reading_properties(properties: PropertiesSource) -> ChunkProjection {+ ChunkProjection::Projected(ColumnPlan {+ uuid: ScalarColumn::Empty,+ elements_chain: ScalarColumn::Keep,+ properties,+ person_properties: BlobSource::Full,+ })+ }++ fn rebuilt(names: &[&str]) -> ChunkProjection {+ let keys = ProjectedKeys::new(names.iter().map(|name| (*name).to_owned()).collect())+ .expect("the test key sets are non-empty");+ reading_properties(PropertiesSource::Blob(BlobSource::Keys(keys)))+ }++ #[test]+ fn properties_come_from_columns_only_when_every_key_is_exact_and_stored() {+ let exact = ColumnExactKeys::exact(["$current_url", "$pathname", "$host"]);+ let stored: MaterializedColumns = [+ ("$current_url", "mat_$current_url"),+ ("$pathname", "mat_$pathname"),+ ("plan", "mat_plan"),+ ]+ .into_iter()+ .collect();+ let upgrade =+ |projection: ChunkProjection| match projection.source_properties(&exact, &stored) {+ PropertiesSourcing::Upgradable(upgrade) => upgrade,+ PropertiesSourcing::Decided(sourced) => panic!("no upgrade offered: {sourced:?}"),+ };++ let both = rebuilt(&["$current_url", "$pathname"]);+ assert!(both.column_candidates(&exact).is_some());+ let accepted = upgrade(both.clone()).accept();+ assert_eq!(accepted.outcome(), PropertiesOutcome::Columns);+ let ChunkProjection::Projected(plan) = accepted.projection() else {+ panic!("an upgrade keeps the chunk projected");+ };+ let PropertiesSource::Columns(columns) = &plan.properties else {+ panic!("expected columns, got {:?}", plan.properties);+ };+ assert_eq!(+ columns+ .iter()+ .map(|(key, column)| (key, column.as_str()))+ .collect::<Vec<_>>(),+ [+ ("$current_url", "mat_$current_url"),+ ("$pathname", "mat_$pathname")+ ]+ );+ assert_eq!(plan.person_properties, BlobSource::Full);+ assert_eq!(plan.elements_chain, ScalarColumn::Keep);++ for (declined, reason) in [+ (+ upgrade(both.clone()).decline_too_long(),+ RebuildReason::TooLong,+ ),+ (+ upgrade(both.clone()).decline_ambiguous_value(),+ RebuildReason::AmbiguousValue,+ ),+ ] {+ assert_eq!(+ (declined.outcome(), declined.into_projection()),+ (PropertiesOutcome::Rebuilt(reason), both.clone())+ );+ }++ let inexact = rebuilt(&["$current_url", "plan"]);+ assert_eq!(inexact.column_candidates(&exact), None);+ for (projection, expected) in [+ (+ inexact,+ PropertiesOutcome::Rebuilt(RebuildReason::Unbacked(Unbacked::InexactKey)),+ ),+ (+ rebuilt(&["$current_url", "$host"]),+ PropertiesOutcome::Rebuilt(RebuildReason::Unbacked(Unbacked::NoColumn)),+ ),+ (ChunkProjection::FullColumns, PropertiesOutcome::Whole),+ (+ reading_properties(PropertiesSource::Blob(BlobSource::Full)),+ PropertiesOutcome::Whole,+ ),+ (+ reading_properties(PropertiesSource::Blob(BlobSource::Empty)),+ PropertiesOutcome::Empty,+ ),+ ] {+ let PropertiesSourcing::Decided(sourced) =+ projection.clone().source_properties(&exact, &stored)+ else {+ panic!("{projection:?} was offered an upgrade");+ };+ assert_eq!(+ (sourced.outcome(), sourced.into_projection()),+ (expected, projection)+ );+ }+ }+#[test]fn the_metric_outcome_names_which_arm_was_taken() {assert_eq!(ChunkProjection::FullColumns.outcome(), "full_columns");diff --git a/rust/cohort-seeder/src/domain/row_filter.rs b/rust/cohort-seeder/src/domain/row_filter.rsindex 1df4610315c1..e4a7270a5566 100644--- a/rust/cohort-seeder/src/domain/row_filter.rs+++ b/rust/cohort-seeder/src/domain/row_filter.rs@@ -7,7 +7,7 @@use std::collections::{BTreeMap, BTreeSet, HashMap};use cohort_core::filters::TeamFilters;-use cohort_core::hogvm::analysis::{EventRowFilter, PropertyAlternatives};+use cohort_core::hogvm::analysis::{EventEqualities, PropertyAlternatives};use super::condition::EventNameSet;use super::ids::ConditionHash;@@ -28,7 +28,7 @@ impl ScanRowFilter {event_names: &EventNameSet,filters: &TeamFilters,active: &ActiveConditions,- row_filters: &HashMap<ConditionHash, EventRowFilter>,+ equalities: &HashMap<ConditionHash, EventEqualities>,) -> Self {let mut by_event = BTreeMap::new();for event in event_names.iter() {@@ -41,7 +41,10 @@ impl ScanRowFilter {let Some(hash) = active.get(candidate) else {continue;};- match row_filters.get(&hash) {+ match equalities+ .get(&hash)+ .and_then(|equalities| equalities.row_filter.as_ref())+ {Some(row_filter) if row_filter.event == *event => {if !conditions.contains(&row_filter.conjuncts) {conditions.push(row_filter.conjuncts.clone());diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rsindex b95a9c29f005..ef5ce77837a5 100644--- a/rust/cohort-seeder/src/observability/metrics.rs+++ b/rust/cohort-seeder/src/observability/metrics.rs@@ -93,6 +93,9 @@ pub const PROJECTION_KEYS: &str = "seeder_projection_keys";/// and `team_id` (counter). Only `materialized` saves ClickHouse reads; `properties_blob` saves the/// transfer and evaluation of rows no condition matches.pub const SCAN_ROW_FILTER: &str = "seeder_scan_row_filter_total";+/// Behavioral chunks by where the scan reads `properties` from, labelled by `source`+/// (`whole`/`empty`/`columns`/`rebuilt_*`) and `team_id` (counter).+pub const SCAN_PROPERTIES_SOURCE: &str = "seeder_scan_properties_source_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/cohort-seeder/tests/ch_event_row_filter.rs b/rust/cohort-seeder/tests/ch_event_row_filter.rsindex 7b987877210c..be4fe01169d8 100644--- a/rust/cohort-seeder/tests/ch_event_row_filter.rs+++ b/rust/cohort-seeder/tests/ch_event_row_filter.rs@@ -13,12 +13,12 @@ use cohort_core::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};use cohort_core::hogvm::analysis::GlobalsPlan;use cohort_core::hogvm::{build_behavioral_globals, evaluate_detailed, EvalOutcome, GlobalsBuild};use cohort_seeder::clickhouse::client::build_client;-use cohort_seeder::clickhouse::materialized::MaterializedColumns;use cohort_seeder::clickhouse::sql::row_filter_sql;use cohort_seeder::clickhouse::ClickHouseClient;use cohort_seeder::config::Config;use cohort_seeder::domain::{- ActiveConditions, ConditionAnalyses, ConditionHash, EventNameSet, Lookback, PinnedCondition,+ ActiveConditions, ColumnName, ConditionAnalyses, ConditionHash, EventNameSet, Lookback,+ MaterializedColumns, PinnedCondition,};use envconfig::Envconfig;use serde::Deserialize;@@ -174,7 +174,7 @@ async fn the_lookup_accepts_only_trim_quotes_columns_on_both_tables() {.await.expect("the lookup reads only system.columns");assert_eq!(- columns.column_for("$feature_flag"),+ columns.column_for("$feature_flag").map(ColumnName::as_str),Some("mat_$feature_flag"));for refused in ["typed", "nullable", "$data_only", "absent"] {diff --git a/rust/cohort-seeder/tests/ch_materialized_properties.rs b/rust/cohort-seeder/tests/ch_materialized_properties.rsnew file mode 100644index 000000000000..460866eb1391--- /dev/null+++ b/rust/cohort-seeder/tests/ch_materialized_properties.rs@@ -0,0 +1,511 @@+//! Checks against a live ClickHouse, with the VM as the oracle, that `properties` built from+//! trim-quotes columns answers exact equalities like the blob, except for the named residuals and+//! the rows the ambiguity probe sends back to the blob.++#![cfg(feature = "ch-test-support")]++use std::collections::{BTreeMap, BTreeSet};++use chrono_tz::UTC;+use clickhouse::Row;+use cohort_core::events::CohortStreamEvent;+use cohort_core::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};+use cohort_core::hogvm::analysis::GlobalsPlan;+use cohort_core::hogvm::{build_behavioral_globals, evaluate_detailed, EvalOutcome, GlobalsBuild};+use cohort_seeder::clickhouse::client::build_client;+use cohort_seeder::clickhouse::sql::{ambiguous_values_sql, columns_object_expr};+use cohort_seeder::clickhouse::ClickHouseClient;+use cohort_seeder::config::Config;+use cohort_seeder::domain::{+ ActiveConditions, ChunkProjection, ColumnBackedKeys, ColumnPlan, ConditionAnalyses,+ ConditionHash, Lookback, MaterializedColumns, PinnedCondition, PropertiesSource,+ PropertiesSourcing,+};+use envconfig::Envconfig;+use serde::Deserialize;+use serde_json::{json, Value};++const DATABASE: &str = "seeder_materialized_properties";+const EVENT: &str = "$pageview";+const URL: &str = "$current_url";+const URL_COLUMN: &str = "mat_$current_url";+/// The materializer sanitizes column names, so only the key is hostile.+const ODD: &str = "quote' \"key\\?";+const ODD_COLUMN: &str = "mat_quote___key__";+const PERSON: &str = r#"{"plan":"pro"}"#;++const LITERALS: &[&str] = &[+ "https://example.com/",+ "https://example.com/p?q=1",+ "a\"b",+ "a\\b",+ "tab\there",+ "é😀",+ "quote' OR 1 = 1 --",+ "{not json",+ "2024-01-01",+ "slash/key",+];++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum Residual {+ /// Every column stores `''` while `serde_json` reads the blob.+ BlobClickHouseCannotParse,+ /// The column holds the first value, `serde_json` the last.+ RepeatedKey,+ /// Comes back typed and too deep for `serde_json`.+ StringHoldingDeepJson,+ /// The blob fails to evaluate while the columns still build an object.+ UnreadableBlob,+}++impl Residual {+ const fn divergence(self) -> Divergence {+ match self {+ Self::UnreadableBlob => Divergence::OverCount,+ Self::BlobClickHouseCannotParse | Self::StringHoldingDeepJson | Self::RepeatedKey => {+ Divergence::UnderCount+ }+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum Divergence {+ OverCount,+ UnderCount,+}++impl Divergence {+ const fn between(from_blob: bool, from_columns: bool) -> Option<Self> {+ match (from_blob, from_columns) {+ (false, true) => Some(Self::OverCount),+ (true, false) => Some(Self::UnderCount),+ (true, true) | (false, false) => None,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Expect {+ Same,+ /// A column reads as `false`, so the scan keeps the blob for the whole chunk.+ Ambiguous,+ Residual(Residual),+}++struct Case {+ blob: String,+ expect: Expect,+}++impl Case {+ fn exact(blob: impl Into<String>) -> Self {+ Self {+ blob: blob.into(),+ expect: Expect::Same,+ }+ }++ fn ambiguous(blob: impl Into<String>) -> Self {+ Self {+ blob: blob.into(),+ expect: Expect::Ambiguous,+ }+ }++ fn residual(blob: impl Into<String>, residual: Residual) -> Self {+ Self {+ blob: blob.into(),+ expect: Expect::Residual(residual),+ }+ }+}++fn corpus() -> Vec<Case> {+ let mut cases: Vec<Case> = [+ r#"{}"#,+ r#"{"other":"https://example.com/"}"#,+ r#"{"$current_url":null}"#,+ r#"{"$current_url":true}"#,+ r#"{"$current_url":5}"#,+ r#"{"$current_url":5.0}"#,+ r#"{"$current_url":-0.0}"#,+ r#"{"$current_url":1e3}"#,+ r#"{"$current_url":["https://example.com/"]}"#,+ r#"{"$current_url":{"https://example.com/":1}}"#,+ r#"{"$current_url":{"__hogDateTime__":true,"dt":1704067200,"zone":"UTC"}}"#,+ r#"{"$current_url":{"__hogDate__":true,"year":2024,"month":1,"day":1}}"#,+ r#"{"$current_url":""}"#,+ r#"{"$current_url":"5"}"#,+ r#"{"$current_url":"5.0"}"#,+ r#"{"$current_url":"1e3"}"#,+ r#"{"$current_url":"true"}"#,+ r#"{"$current_url":"TRUE"}"#,+ r#"{"$current_url":"null"}"#,+ r#"{"$current_url":"{}"}"#,+ r#"{"$current_url":"[1]"}"#,+ r#"{"$current_url":" 5"}"#,+ r#"{"$current_url":"https:\/\/example.com\/"}"#,+ r#"{"$current_url":"https://example.com/"}"#,+ r#"{ "$current_url" : "https://example.com/" , "other" : 1 }"#,+ r#"{"nested":{"$current_url":"https://example.com/"}}"#,+ r#""https://example.com/""#,+ r#"null"#,+ r#""#,+ ]+ .into_iter()+ .map(Case::exact)+ .collect();+ cases.extend(+ [r#"["https://example.com/"]"#, r#"{not json"#]+ .map(|blob| Case::residual(blob, Residual::UnreadableBlob)),+ );+ for literal in LITERALS {+ let escaped = literal+ .encode_utf16()+ .map(|unit| format!("\\u{unit:04x}"))+ .collect::<String>();+ cases.extend([+ Case::exact(json!({ URL: literal }).to_string()),+ Case::exact(json!({ ODD: literal }).to_string()),+ Case::exact(json!({ URL: literal, ODD: literal, "pad": "x" }).to_string()),+ Case::exact(format!(r#"{{"{URL}":"{escaped}"}}"#)),+ ]);+ }+ cases.extend([+ Case::ambiguous(r#"{"$current_url":false}"#),+ Case::ambiguous(r#"{"$current_url":"false"}"#),+ Case::ambiguous(r#"{"$current_url":" false "}"#),+ Case::ambiguous(json!({ URL: "https://example.com/", ODD: "false" }).to_string()),+ Case::residual(+ r#"{"$current_url":"elsewhere","$current_url":"https://example.com/"}"#,+ Residual::RepeatedKey,+ ),+ Case::residual(+ r#"{"$current_url":"https://example.com/","n":18446744073709551616}"#,+ Residual::BlobClickHouseCannotParse,+ ),+ Case::residual(+ json!({+ URL: "https://example.com/",+ ODD: format!("{}{}", "[".repeat(200), "]".repeat(200)),+ })+ .to_string(),+ Residual::StringHoldingDeepJson,+ ),+ ]);+ cases+}++#[derive(Row, Deserialize)]+struct Rebuilt {+ seq: u32,+ properties: String,+ ambiguous: bool,+}++#[tokio::test]+async fn columns_answer_every_exact_equality_like_the_blob_but_the_named_residuals() {+ let (filters, conditions) = catalog();+ let columns = column_backed_properties(&filters, &conditions);+ let programs = conditions+ .iter()+ .map(|condition| {+ filters+ .by_condition_to_program+ .get(&condition.hash.as_bytes())+ .expect("the catalog loads every condition's program")+ .tokens()+ .to_vec()+ })+ .collect::<Vec<_>>();+ let corpus = corpus();+ let rebuilt = rebuild_all(&corpus, &columns).await;++ assert_eq!(+ corpus+ .iter()+ .zip(&rebuilt)+ .filter(|(_, row)| row.ambiguous)+ .map(|(case, _)| case.blob.as_str())+ .collect::<Vec<_>>(),+ corpus+ .iter()+ .filter(|case| case.expect == Expect::Ambiguous)+ .map(|case| case.blob.as_str())+ .collect::<Vec<_>>(),+ "the probe flagged other rows than those whose columns read as false"+ );++ for (+ case,+ Rebuilt {+ properties: rebuilt,+ ..+ },+ ) in corpus.iter().zip(&rebuilt)+ {+ match serde_json::from_str::<Value>(rebuilt) {+ Ok(Value::Object(object)) => assert_eq!(+ object.keys().map(String::as_str).collect::<Vec<_>>(),+ [URL, ODD],+ "{} rebuilt as {rebuilt}",+ case.blob+ ),+ Ok(other) => panic!("{} rebuilt as a non-object {other}", case.blob),+ Err(error) => assert_eq!(+ case.expect,+ Expect::Residual(Residual::StringHoldingDeepJson),+ "{} rebuilt as {rebuilt}, which does not parse: {error}",+ case.blob+ ),+ }+ }++ let divergences: BTreeMap<usize, BTreeSet<Divergence>> = corpus+ .iter()+ .zip(&rebuilt)+ .enumerate()+ .filter(|(_, (_, row))| !row.ambiguous)+ .filter_map(|(index, (case, row))| {+ let found = programs+ .iter()+ .filter_map(|program| {+ Divergence::between(+ program_matches(program, &case.blob),+ program_matches(program, &row.properties),+ )+ })+ .collect::<BTreeSet<_>>();+ (!found.is_empty()).then_some((index, found))+ })+ .collect();++ let expected: BTreeMap<usize, BTreeSet<Divergence>> = corpus+ .iter()+ .enumerate()+ .filter_map(|(index, case)| {+ let Expect::Residual(residual) = case.expect else {+ return None;+ };+ Some((index, BTreeSet::from([residual.divergence()])))+ })+ .collect();+ let describe = |map: &BTreeMap<usize, BTreeSet<Divergence>>| {+ map.iter()+ .map(|(index, directions)| format!("{} {directions:?}", corpus[*index].blob))+ .collect::<Vec<_>>()+ };+ assert_eq!(+ describe(&divergences),+ describe(&expected),+ "the column form diverged from the blob somewhere other than the named residuals"+ );+}++fn catalog() -> (TeamFilters, Vec<PinnedCondition>) {+ let mut builder = TeamFiltersBuilder::default();+ let mut conditions = Vec::new();+ let equalities = [URL, ODD].into_iter().flat_map(|key| {+ LITERALS.iter().map(move |literal| {+ json!([+ "_H",+ 1,+ 32,+ EVENT,+ 32,+ "event",+ 1,+ 1,+ 11,+ 32,+ literal,+ 32,+ key,+ 32,+ "properties",+ 1,+ 2,+ 11,+ 3,+ 2+ ])+ })+ });+ let with_person = json!([+ "_H",+ 1,+ 32,+ EVENT,+ 32,+ "event",+ 1,+ 1,+ 11,+ 32,+ "https://example.com/",+ 32,+ URL,+ 32,+ "properties",+ 1,+ 2,+ 11,+ 32,+ "pro",+ 32,+ "plan",+ 32,+ "properties",+ 32,+ "person",+ 1,+ 3,+ 11,+ 4,+ 2,+ 3,+ 2+ ]);+ let programs = equalities.chain([with_person]);+ for (index, bytecode) in programs.enumerate() {+ let hash = format!("{index:016}");+ let cohort = CohortId(i32::try_from(index).expect("the catalog is small") + 1);+ builder+ .add_cohort(+ cohort,+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": EVENT,+ "conditionHash": hash,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": bytecode,+ }]}+ }),+ )+ .expect("the test catalog parses");+ conditions.push(PinnedCondition {+ cohort_id: cohort,+ hash: ConditionHash::parse(&hash).expect("the hash is 16 ASCII bytes"),+ event_name: EVENT.to_owned(),+ lookback: Lookback::SlidingDays(7),+ });+ }+ (builder.freeze(UTC), conditions)+}++fn column_backed_properties(+ filters: &TeamFilters,+ conditions: &[PinnedCondition],+) -> ColumnBackedKeys {+ let analyses = ConditionAnalyses::build(conditions, filters);+ let active = ActiveConditions::new(conditions.iter().map(|condition| condition.hash));+ let columns: MaterializedColumns = [(URL, URL_COLUMN), (ODD, ODD_COLUMN)].into_iter().collect();+ let sourcing = analyses+ .projection(&active)+ .source_properties(&analyses.column_exact_keys(&active), &columns);+ let PropertiesSourcing::Upgradable(upgrade) = sourcing else {+ panic!("the analysis did not find every key exact: {sourcing:?}");+ };+ match upgrade.accept().into_projection() {+ ChunkProjection::Projected(ColumnPlan {+ properties: PropertiesSource::Columns(columns),+ ..+ }) => columns,+ other => panic!("an accepted upgrade returned {other:?}"),+ }+}++async fn rebuild_all(corpus: &[Case], columns: &ColumnBackedKeys) -> Vec<Rebuilt> {+ let admin = connect(None);+ for statement in [+ format!("DROP DATABASE IF EXISTS {DATABASE}"),+ format!("CREATE DATABASE {DATABASE}"),+ format!(+ "CREATE TABLE {DATABASE}.events (seq UInt32, properties String, `{URL_COLUMN}` String DEFAULT {}, `{ODD_COLUMN}` String DEFAULT {}) ENGINE = MergeTree ORDER BY seq",+ trim_quotes_extraction(URL),+ trim_quotes_extraction(ODD),+ ),+ ] {+ admin+ .query(&statement)+ .execute()+ .await+ .unwrap_or_else(|error| panic!("{error}\n{statement}"));+ }+ let client = connect(Some(DATABASE));+ client+ .query("INSERT INTO events (seq, properties) SELECT seq, blobs[seq] FROM (SELECT ? AS blobs, arrayJoin(arrayEnumerate(blobs)) AS seq)")+ .bind(corpus.iter().map(|case| case.blob.as_str()).collect::<Vec<_>>())+ .execute()+ .await+ .expect("the corpus inserts");++ let sql = format!(+ "SELECT seq, {} AS properties, {} AS ambiguous FROM events AS e ORDER BY seq",+ columns_object_expr(columns),+ ambiguous_values_sql(columns),+ );+ assert!(+ !sql.contains("e.properties"),+ "the column form reads the blob: {sql}"+ );+ let rows = client+ .query(&sql)+ .fetch_all::<Rebuilt>()+ .await+ .unwrap_or_else(|error| panic!("the column form failed: {error}\n{sql}"));+ assert_eq!(rows.len(), corpus.len(), "a row went missing: {sql}");+ for (position, row) in rows.iter().enumerate() {+ assert_eq!(row.seq as usize, position + 1, "rows arrived out of order");+ }+ rows+}++/// The materializer's expression, with `?` doubled for the client's binds.+fn trim_quotes_extraction(key: &str) -> String {+ let escaped = key+ .replace('\\', "\\\\")+ .replace('\'', "\\'")+ .replace('?', "??");+ format!("replaceRegexpAll(JSONExtractRaw(properties, '{escaped}'), '^\"|\"$', '')")+}++fn connect(database: Option<&str>) -> ClickHouseClient {+ let mut config = Config::init_from_env().expect("the seeder config falls back to its defaults");+ if let Some(database) = database {+ config.clickhouse_database = database.to_owned();+ }+ build_client(&config).expect("the default ClickHouse client builds")+}++fn program_matches(program: &[Value], blob: &str) -> bool {+ let event = CohortStreamEvent {+ team_id: 2,+ person_id: "0190c3a5-0000-7000-8000-000000000001".to_owned(),+ distinct_id: "distinct".to_owned(),+ uuid: "0190c3a5-0000-7000-8000-000000000002".to_owned(),+ event: EVENT.to_owned(),+ timestamp: "2024-01-01 00:00:00.000000".to_owned(),+ properties: (!blob.is_empty()).then(|| blob.to_owned()),+ person_properties: Some(PERSON.to_owned()),+ elements_chain: None,+ source_offset: 0,+ source_partition: -1,+ redirected_from: None,+ redirect_hops: 0,+ };+ let Ok(globals) = build_behavioral_globals(&event, GlobalsBuild::whole(GlobalsPlan::FULL))+ else {+ return false;+ };+ matches!(+ evaluate_detailed(program, globals),+ EvalOutcome::Matched(true)+ )+}