Skip to content

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

perf(cohorts): project the seeder scan onto the columns conditions read (#92009)

Matheus Batista0315b9c38cd5
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 6610cffb1304..93b2c0653213 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -496,7 +496,14 @@ jobs:
extra_args="--test-threads=4"
fi
if [ "$pkg" = "cohort-seeder" ] && [ -f cohort-seeder/Cargo.toml ] && grep -q '^pg-test-support[[:space:]]*=' cohort-seeder/Cargo.toml; then
- DATABASE_URL='postgres://posthog:posthog@localhost:5432/test_posthog' run_nextest "$pkg" -p "$pkg" --features pg-test-support $extra_args || overall_rc=1
+ features="pg-test-support"
+ # ch-test-support arms the live-ClickHouse rebuild corpus against the
+ # compose stack's clickhouse; the grep keeps branches that predate the
+ # feature building.
+ if grep -q '^ch-test-support[[:space:]]*=' cohort-seeder/Cargo.toml; then
+ features="pg-test-support,ch-test-support"
+ fi
+ DATABASE_URL='postgres://posthog:posthog@localhost:5432/test_posthog' run_nextest "$pkg" -p "$pkg" --features "$features" $extra_args || overall_rc=1
else
run_nextest "$pkg" -p "$pkg" $extra_args || overall_rc=1
fi
diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rs
index 887a596dc5ba..d43fc831353e 100644
--- a/rust/cohort-core/src/hogvm/analysis/mod.rs
+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs
@@ -63,14 +63,19 @@ pub enum Projection {
FullColumns(FullColumnsReason),
}
-/// Why a condition fell back to every column. The two bare-root cases are ordinary programs whose
-/// reads genuinely cannot be narrowed; [`FullColumnsReason::Unanalyzable`] is the fail-closed arm.
+/// Why a condition fell back to every column. Every case but [`FullColumnsReason::Unanalyzable`] is
+/// an ordinary program the analysis understood and still cannot narrow; that one is the fail-closed
+/// arm, where the model lost track of the program.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FullColumnsReason {
/// The program passes the whole `properties` dict somewhere, for example to a function.
BarePropertiesRoot,
/// The program passes the whole `person` object somewhere.
BarePersonRoot,
+ /// The program calls a native that reads how a number was spelled rather than what it is, so a
+ /// caller supplying the claimed paths from re-serialized JSON would change the answer. The read
+ /// set itself is exact; what cannot be narrowed is how it may be supplied.
+ RepresentationSensitiveCall,
Unanalyzable(UnanalyzableReason),
}
@@ -80,6 +85,7 @@ impl FullColumnsReason {
match self {
Self::BarePropertiesRoot => "bare_properties_root",
Self::BarePersonRoot => "bare_person_root",
+ Self::RepresentationSensitiveCall => "representation_sensitive_call",
Self::Unanalyzable(reason) => reason.as_str(),
}
}
@@ -88,6 +94,7 @@ impl FullColumnsReason {
pub fn op(&self) -> Option<Operation> {
match self {
Self::Unanalyzable(reason) => reason.op(),
+ Self::RepresentationSensitiveCall => Some(Operation::CallGlobal),
Self::BarePropertiesRoot | Self::BarePersonRoot => None,
}
}
diff --git a/rust/cohort-core/src/hogvm/analysis/projection.rs b/rust/cohort-core/src/hogvm/analysis/projection.rs
index bcf3c2e20eb1..aa7bfcc38a19 100644
--- a/rust/cohort-core/src/hogvm/analysis/projection.rs
+++ b/rust/cohort-core/src/hogvm/analysis/projection.rs
@@ -43,6 +43,27 @@ use super::{FullColumnsReason, GlobalRoot, Projection, ReadPath, UnanalyzableRea
/// that projects an `elements_chain` read must carry it too.
const ELEMENTS_CHAIN_PROPERTY: &str = "$elements_chain";
+/// Natives whose result depends on how a JSON number was spelled, rather than on its value.
+///
+/// A caller acting on [`Projection::Reads`] supplies the claimed paths through its own storage, and
+/// the seeder supplies them by having ClickHouse rebuild the blob from the kept keys. That rebuild
+/// re-prints every number it copies, so a whole-number float token arrives as an integer one:
+/// `{"n": 100.0}` becomes `{"n": 100}`, which the VM loads as `Num::Integer(100)` where live
+/// evaluation loads `Num::Float(100.0)`.
+///
+/// Most of the VM cannot see that. Equality unifies the two variants, arithmetic and ordering widen
+/// a mixed pair to `f64`, and the printer renders `Float(100.0)` and `Integer(100)` as the same
+/// text. The exceptions are the natives below, each of which branches on `Num::is_float` in a way
+/// that reaches its result: `typeof` answers `"float"` or `"integer"`, and `jsonStringify` keeps the
+/// decimal point only for the float variant. A condition calling either would seed a membership its
+/// live evaluation disagrees with, so the whole condition takes every column instead.
+///
+/// One residual is accepted rather than covered. `print_hog_value` renders an object carrying an
+/// `__hx_ast` key back to SQL, and that printer does distinguish the variants, so `toString` of a
+/// property whose value is shaped like a HogQL AST node is sensitive too. That needs a customer
+/// blob built to look like compiler output, which no filter the product writes can produce.
+const REPRESENTATION_SENSITIVE_NATIVES: [&str; 2] = ["typeof", "jsonStringify"];
+
/// A ceiling on transfer steps one program may take, so a program the lattice argument does not
/// cover cannot hang the caller. The fixpoint is reached far sooner: a merge point's stack can only
/// move upward, one cell at a time, so the work is quadratic in the program length at worst and
@@ -196,7 +217,7 @@ pub(super) fn project(bytecode: &[Value], budget: &mut AnalysisBudget) -> Projec
match outcome {
Ok(reads) => Projection::Reads(reads),
Err(Stop::Unanalyzable(reason)) => full_columns(reason),
- Err(Stop::BareRoot(reason)) => Projection::FullColumns(reason),
+ Err(Stop::Unnarrowable(reason)) => Projection::FullColumns(reason),
}
}
@@ -204,11 +225,11 @@ fn full_columns(reason: UnanalyzableReason) -> Projection {
Projection::FullColumns(FullColumnsReason::Unanalyzable(reason))
}
-/// Why the interpreter stopped early. A bare root is an ordinary program the analysis understood
-/// and cannot narrow; everything else is the fail-closed arm.
+/// Why the interpreter stopped early. [`Stop::Unnarrowable`] is an ordinary program the analysis
+/// understood and cannot narrow; everything else is the fail-closed arm.
enum Stop {
Unanalyzable(UnanalyzableReason),
- BareRoot(FullColumnsReason),
+ Unnarrowable(FullColumnsReason),
}
/// What an instruction does to control flow, after its own stack effect has been applied. Both
@@ -433,9 +454,18 @@ impl<'a> Interpreter<'a> {
}
InstrKind::Number(_) => push_opaque(stack),
InstrKind::Counted(op, count) => self.counted(*op, *count, stack),
- // Any callee name is projection-safe. A native consumes stack values and cannot reach
- // the globals dict, which is what keeps `toDateTime(timestamp) > x` projectable.
- InstrKind::CallGlobal { argc, .. } => reduce(stack, *argc),
+ // A native consumes stack values and cannot reach the globals dict, so it never widens
+ // the read set — which is what keeps `toDateTime(timestamp) > x` projectable. The
+ // exception is a native that reads a value's *spelling* rather than its value; see
+ // [`REPRESENTATION_SENSITIVE_NATIVES`].
+ InstrKind::CallGlobal { name, argc } => {
+ if REPRESENTATION_SENSITIVE_NATIVES.contains(&name.as_str()) {
+ return Err(Stop::Unnarrowable(
+ FullColumnsReason::RepresentationSensitiveCall,
+ ));
+ }
+ reduce(stack, *argc)
+ }
InstrKind::Bare(op) => self.bare(*op, stack),
InstrKind::Branch { op, target } => branch(*op, *target, stack),
// A callable or closure introduces a frame the model has no notion of, and `TRY`
@@ -583,10 +613,10 @@ impl<'a> Interpreter<'a> {
if segments.is_empty() {
match root {
GlobalRoot::Properties => {
- return Err(Stop::BareRoot(FullColumnsReason::BarePropertiesRoot))
+ return Err(Stop::Unnarrowable(FullColumnsReason::BarePropertiesRoot))
}
GlobalRoot::Person | GlobalRoot::Pdi => {
- return Err(Stop::BareRoot(FullColumnsReason::BarePersonRoot))
+ return Err(Stop::Unnarrowable(FullColumnsReason::BarePersonRoot))
}
_ => {}
}
@@ -1044,18 +1074,49 @@ mod tests {
assert_eq!(reads(tokens), ["properties.plan"]);
}
- /// A native call is projection-safe whatever its name, because it only consumes stack values.
- /// Refusing them would make every `toDateTime(timestamp) > x` condition unprojectable.
+ /// An ordinary native call is projection-safe, because it only consumes stack values. Refusing
+ /// every native would make every `toDateTime(timestamp) > x` condition unprojectable.
#[test]
fn a_native_call_over_a_read_keeps_the_read_precise() {
+ assert_eq!(reads(call_over_timestamp("toDateTime")), ["timestamp"]);
+ }
+
+ /// A native that reads a number's spelling is the one call the read set cannot describe: the
+ /// paths are right, but supplying them from re-serialized JSON changes the answer. See
+ /// [`REPRESENTATION_SENSITIVE_NATIVES`]. Reported as an understood program rather than as a
+ /// failure, because nothing about it escaped the model.
+ #[test]
+ fn a_representation_sensitive_native_widens_to_every_column() {
+ for name in REPRESENTATION_SENSITIVE_NATIVES {
+ assert_eq!(
+ full_columns_reason(call_over_timestamp(name)),
+ FullColumnsReason::RepresentationSensitiveCall,
+ "{name}"
+ );
+ }
+ }
+
+ /// The refusal is on the call, not on the read under it: a program that never calls one of
+ /// these keeps its narrow answer however many other natives it uses.
+ #[test]
+ fn a_sensitive_native_name_only_matters_when_it_is_called() {
+ assert_eq!(reads(call_over_timestamp("toTypeOf")), ["timestamp"]);
+ assert_eq!(
+ reads(read(&["properties", "typeof"])),
+ ["properties.typeof"]
+ );
+ }
+
+ /// `name(timestamp) > '2026-01-01'`.
+ fn call_over_timestamp(name: &str) -> Vec<Value> {
let mut tokens = read(&["timestamp"]);
tokens.push(json!(2));
- tokens.push(json!("toDateTime"));
+ tokens.push(json!(name));
tokens.push(json!(1));
tokens.push(json!(32));
tokens.push(json!("2026-01-01"));
tokens.push(json!(13));
- assert_eq!(reads(tokens), ["timestamp"]);
+ tokens
}
/// A hostile count immediate must not reach an allocation. `u64::MAX` is a capacity-overflow
diff --git a/rust/cohort-core/tests/analysis_representation.rs b/rust/cohort-core/tests/analysis_representation.rs
new file mode 100644
index 000000000000..dc7914ed4de9
--- /dev/null
+++ b/rust/cohort-core/tests/analysis_representation.rs
@@ -0,0 +1,123 @@
+//! Pins the reason the analysis refuses a few natives outright: a caller supplying a claimed read
+//! path from re-serialized JSON hands the VM a number of the other variant.
+//!
+//! The seeder's projected scan has ClickHouse rebuild a blob from the keys a chunk reads, and that
+//! rebuild re-prints every number it copies, so a `100.0` token arrives as `100`. Most of the VM
+//! cannot see the difference. The tests below run both spellings through the real evaluator and
+//! sort the natives by whether it can: the ones that answer differently must widen the condition to
+//! every column, and the ones that do not must stay narrow, because widening them would give back
+//! the projection on ordinary conditions.
+//!
+//! Written as evaluations rather than as assertions about the STL, so a native that starts or stops
+//! reading a number's spelling is caught here rather than in a list nobody re-reads.
+
+use cohort_core::hogvm::analysis::{analyze_condition, FullColumnsReason, Projection};
+use cohort_core::{evaluate_detailed, EvalOutcome};
+use serde_json::{json, Value};
+
+/// `<native>(properties.n) == <expected>`, in the shape the cohort compiler emits: the operands are
+/// pushed before the comparison, and a global chain is pushed leaf first.
+fn compare_native_over_property(native: &str, expected: &str) -> Vec<Value> {
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!(expected),
+ json!(32),
+ json!("n"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(2),
+ json!(native),
+ json!(1),
+ json!(11),
+ json!(38),
+ ]
+}
+
+/// The two spellings of one hundred: what the event carries, and what a rebuilt blob returns.
+fn both_spellings() -> [Value; 2] {
+ [
+ json!({ "properties": { "n": 100.0 } }),
+ json!({ "properties": { "n": 100 } }),
+ ]
+}
+
+fn verdict(bytecode: &[Value], globals: Value) -> bool {
+ match evaluate_detailed(bytecode, globals) {
+ EvalOutcome::Matched(matched) => matched,
+ other => panic!("the probe program did not evaluate: {other:?}"),
+ }
+}
+
+/// The natives on the refusal list really do read the spelling. Without this, the list reads as
+/// caution rather than as a measurement, and the next person to widen it has nothing to check
+/// against.
+#[test]
+fn a_refused_native_answers_differently_for_the_two_spellings() {
+ for (native, expected) in [("typeof", "float"), ("jsonStringify", "100.0")] {
+ let bytecode = compare_native_over_property(native, expected);
+ let [as_written, as_rebuilt] = both_spellings();
+ assert!(
+ verdict(&bytecode, as_written),
+ "{native} did not match the float spelling, so the probe proves nothing"
+ );
+ assert!(
+ !verdict(&bytecode, as_rebuilt),
+ "{native} answered the same for both spellings and no longer needs refusing"
+ );
+ }
+}
+
+/// The same probe over the natives and operators the cohort UI actually emits. These stay
+/// projectable, and this is what says the refusal above is narrow rather than a blanket ban on
+/// calls: `toString` prints both spellings as `100`, and equality unifies the variants.
+#[test]
+fn an_ordinary_condition_reads_the_two_spellings_the_same_way() {
+ let bare_equality = vec![
+ json!("_H"),
+ json!(1),
+ json!(33),
+ json!(100),
+ json!(32),
+ json!("n"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(11),
+ json!(38),
+ ];
+ for bytecode in [
+ compare_native_over_property("toString", "100"),
+ bare_equality,
+ ] {
+ let [as_written, as_rebuilt] = both_spellings();
+ assert!(verdict(&bytecode, as_written), "{bytecode:?}");
+ assert!(verdict(&bytecode, as_rebuilt), "{bytecode:?}");
+ }
+}
+
+/// The analysis has to act on the split above: the programs that diverge take every column, and the
+/// ones that do not keep their narrow read set.
+#[test]
+fn the_analysis_widens_exactly_the_conditions_that_diverge() {
+ for native in ["typeof", "jsonStringify"] {
+ assert_eq!(
+ analyze_condition(&compare_native_over_property(native, "x")).projection,
+ Projection::FullColumns(FullColumnsReason::RepresentationSensitiveCall),
+ "{native} still projects, so a rebuilt blob would reach it"
+ );
+ }
+ let Projection::Reads(paths) =
+ analyze_condition(&compare_native_over_property("toString", "100")).projection
+ else {
+ panic!("an ordinary native call must keep its read set");
+ };
+ assert_eq!(
+ paths.iter().map(|path| path.render()).collect::<Vec<_>>(),
+ ["properties.n"]
+ );
+}
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index 39ba70b48c15..d5e523d0620b 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -8,6 +8,8 @@ workspace = true
[features]
pg-test-support = []
+# Arms the tests that need a reachable ClickHouse, which the rust CI job's compose stack provides.
+ch-test-support = []
[[bin]]
name = "reconcile_dispatch"
diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rs
index 2323b1f3ae94..43e2239f5a41 100644
--- a/rust/cohort-seeder/src/app/execute.rs
+++ b/rust/cohort-seeder/src/app/execute.rs
@@ -15,8 +15,8 @@ use tracing::{info, warn};
use crate::clickhouse::scanner::ChunkScanner;
use crate::domain::{
- ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, PinnedRun,
- ProducedChunk, RetryBackoffPolicy, ScannedChunk, StreamedChunk,
+ ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProducedChunk,
+ RetryBackoffPolicy, ScannedChunk, StreamedChunk,
};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
@@ -27,13 +27,14 @@ use crate::store::runs::RunKind;
use crate::store::RenderedError;
use super::deliver::{self, ProduceError};
+use super::prepare::PreparedBehavioral;
use super::settings::ProducerSettings;
/// The owned inputs to one chunk's processing task, bundled so the spawn stays tidy.
pub(super) struct ChunkTaskContext {
pub(super) chunk: ClaimedChunk,
pub(super) lease: LeaseHandle,
- pub(super) run: Arc<PinnedRun>,
+ pub(super) prepared: Arc<PreparedBehavioral>,
pub(super) store: PgChunkStore,
pub(super) scanner: ChunkScanner,
pub(super) producer: SeedTileProducer,
@@ -49,7 +50,7 @@ pub(super) async fn execute_chunk(
let ChunkTaskContext {
chunk,
lease,
- run,
+ prepared,
store,
scanner,
producer,
@@ -60,7 +61,16 @@ pub(super) async fn execute_chunk(
let lease_cancel = lease.cancellation_token();
// PreMark: scan history into tiles.
- let scanned = match scanner.scan(chunk, &run, &lease_cancel, &shutdown).await {
+ let scanned = match scanner
+ .scan(
+ chunk,
+ &prepared.run,
+ &prepared.analyses,
+ &lease_cancel,
+ &shutdown,
+ )
+ .await
+ {
Ok(scanned) => scanned,
Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index fcd8d9fb8f6c..9248a9a1d301 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -372,12 +372,12 @@ impl SeederOrchestrator {
continue;
};
match prepared {
- PreparedRun::Behavioral(run) => {
+ PreparedRun::Behavioral(prepared) => {
record_claim(kind, RunKind::Behavioral);
let ctx = ChunkTaskContext {
chunk,
lease,
- run: run.clone(),
+ prepared: prepared.clone(),
store: self.store.clone(),
scanner: self.scanner.clone(),
producer: self.producer.clone(),
diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rs
index aad064c95761..06c4129f766c 100644
--- a/rust/cohort-seeder/src/app/prepare.rs
+++ b/rust/cohort-seeder/src/app/prepare.rs
@@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use cohort_core::bucket_tz::window_start_for_now;
-use cohort_core::filters::{CohortId, TeamId};
+use cohort_core::filters::CohortId;
use common_types::cohort::TeamAllowlist;
use metrics::{counter, gauge};
use sqlx::PgPool;
@@ -22,7 +22,7 @@ use crate::domain::{
PinnedRun, PinnedWarning, PlanCaps, RunId,
};
use crate::observability::metrics::{
- BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_CLASSIFIED,
+ team_label, BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_CLASSIFIED,
CONDITIONS_DROPPED, CONDITIONS_UNANALYZABLE, LOOKBACK_TRUNCATED, RUNS_DISCOVERED,
RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS,
RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
@@ -39,10 +39,21 @@ use super::person_plan::PersonPlanRequest;
/// A run validated to the point of claim eligibility, by kind.
pub(super) enum PreparedRun {
- Behavioral(Arc<PinnedRun>),
+ Behavioral(Arc<PreparedBehavioral>),
Person(Arc<PinnedPersonRun>),
}
+/// A behavioral run and the static analysis of its conditions, which every chunk of it shares.
+///
+/// The analysis lives here rather than on the scan because it is a pure function of the pinned
+/// payload: a run's answer is the same for all of its chunks, for a chunk retried after a failure,
+/// and on whichever replica claims it. Deriving it per chunk instead would re-walk the whole
+/// condition catalog up to once per planned day per attempt, on the worker that owes the scan.
+pub(super) struct PreparedBehavioral {
+ pub(super) run: PinnedRun,
+ pub(super) analyses: ConditionAnalyses,
+}
+
/// One refresh pass's result: the claim-eligible runs plus the person runs still needing their
/// planning scan.
pub(super) struct RefreshOutcome {
@@ -90,7 +101,7 @@ pub(super) async fn refresh_runs(
match prepare_run(pool, store, allowlist, plan_caps, reported_runs, run).await {
PrepareOutcome::Eligible(prepared) => {
let run_id = match &prepared {
- PreparedRun::Behavioral(run) => run.run_id,
+ PreparedRun::Behavioral(prepared) => prepared.run.run_id,
PreparedRun::Person(run) => run.run_id,
};
eligible.insert(run_id, prepared);
@@ -199,9 +210,10 @@ async fn prepare_behavioral(
}
};
let lookback_truncated = lookback_was_truncated(&validated.run, plan_caps);
+ let analyses = ConditionAnalyses::build(&validated.run.conditions, &validated.run.filters);
if reported_runs.insert(run_id) {
record_pinned_warnings(&validated.warnings);
- record_condition_census(allowlist, run_id, &validated.run);
+ record_condition_census(allowlist, run_id, &validated.run, &analyses);
if lookback_truncated {
counter!(LOOKBACK_TRUNCATED).increment(1);
}
@@ -260,7 +272,10 @@ async fn prepare_behavioral(
return PrepareOutcome::Skipped;
}
}
- PrepareOutcome::Eligible(PreparedRun::Behavioral(Arc::new(validated.run)))
+ PrepareOutcome::Eligible(PreparedRun::Behavioral(Arc::new(PreparedBehavioral {
+ run: validated.run,
+ analyses,
+ })))
}
/// The person pipeline: validate the pinned payload (zero surviving hashes with an active
@@ -400,24 +415,23 @@ async fn persist_run_warning(pool: &PgPool, run_id: RunId, note: RunWarningNote)
}
}
-/// Publish what a static read of the run's condition bytecode found.
+/// Publish what a static read of the run's condition bytecode found: which event names a projection
+/// narrows, and what blocks the rest.
///
-/// The analysis is built here rather than during validation, so it runs exactly once per run per
-/// stretch: this is already behind the `reported_runs` gate, where validation is not. Validation
-/// runs every poll tick, and the decode is the one place the seeder interprets an untrusted catalog
-/// value.
-///
-/// This runs inline on the task that owes the liveness heartbeat, so its cost has to be bounded by
-/// the run rather than by the condition: nothing caps behavioral conditions on a run, and the
-/// `reported_runs` gate does not help after a restart, when every active run is new again.
-/// `ConditionAnalyses::build` gives the run's conditions one shared budget for that. The gate is
-/// still what keeps the *ordinary* cost small — the same tick already parses every discovered run's
-/// whole pinned payload during validation, which is more work than analyzing that payload once.
-///
-/// Nothing consumes the analysis yet. The point is to learn the shape of real catalogs before any
-/// scan is built on one: which event names a projection could narrow, and what blocks the rest.
-fn record_condition_census(allowlist: &TeamAllowlist, run_id: RunId, run: &PinnedRun) {
- let census = ConditionAnalyses::build(&run.conditions, &run.filters).census(&run.conditions);
+/// Reports once per run per stretch, behind the `reported_runs` gate, while the analysis it reads is
+/// built for every eligible run on every poll tick — the scan needs it, so it cannot sit behind a
+/// report gate. That cost is bounded per run rather than per condition, which matters because
+/// nothing caps behavioral conditions on a run and this runs inline on the task that owes the
+/// liveness heartbeat: `ConditionAnalyses::build` gives the run's conditions one shared budget. The
+/// same tick already parses every discovered run's whole pinned payload during validation, which is
+/// more work than analyzing that payload once.
+fn record_condition_census(
+ allowlist: &TeamAllowlist,
+ run_id: RunId,
+ run: &PinnedRun,
+ analyses: &ConditionAnalyses,
+) {
+ let census = analyses.census(&run.conditions);
if census.total() == 0 {
return;
}
@@ -468,32 +482,6 @@ fn record_condition_census(allowlist: &TeamAllowlist, run_id: RunId, run: &Pinne
);
}
-/// How many teams the census names individually before it stops naming any.
-///
-/// Sized well above the shadow rollout's team count, so the collapse is a ceiling rather than a
-/// routine truncation.
-const MAX_LABELLED_TEAMS: usize = 32;
-
-/// The label every team shares once the census stops naming them.
-const UNLABELLED_TEAM: &str = "other";
-
-/// The team a census belongs to, as a metric label.
-///
-/// A team gets its own series only while `REALTIME_COHORT_TEAM_ALLOWLIST` names few enough of them.
-/// The allowlist does not bound this on its own: it accepts `all` (which a set-but-empty variable
-/// also parses to) and ranges of up to 100,000 ids, and the recorder never evicts a series, so a
-/// wide rollout would retain one per team that ever seeded. The label is here because the
-/// deliverable is one team's number, which a blended counter cannot give; the per-run log line
-/// carries the exact team either way, so collapsing costs the dashboard, not the answer.
-fn team_label(allowlist: &TeamAllowlist, team_id: TeamId) -> Arc<str> {
- match allowlist {
- TeamAllowlist::Only(ids) if ids.len() <= MAX_LABELLED_TEAMS => {
- Arc::from(team_id.0.to_string().as_str())
- }
- TeamAllowlist::Only(_) | TeamAllowlist::All => Arc::from(UNLABELLED_TEAM),
- }
-}
-
fn record_pinned_warnings(warnings: &[PinnedWarning]) {
for warning in warnings {
match warning {
@@ -563,34 +551,3 @@ fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDis
| RunError::NotActive(_) => RunErrorDisposition::Retry,
}
}
-
-#[cfg(test)]
-mod tests {
- use std::collections::HashSet;
-
- use super::*;
-
- /// An allowlist that can grow with the customer base must not mint a metric series per team.
- /// The recorder never evicts one, so a label that tracks team count leaks for the whole process
- /// lifetime — and `all`, which a set-but-empty variable also parses to, is the configuration
- /// the boundedness claim used to assume away.
- #[test]
- fn only_a_narrow_allowlist_names_teams_in_the_census_label() {
- let narrow = TeamAllowlist::Only(HashSet::from([2, 7]));
- assert_eq!(&*team_label(&narrow, TeamId(2)), "2");
-
- let wide = TeamAllowlist::Only((0..=MAX_LABELLED_TEAMS as i32).collect());
- assert_eq!(&*team_label(&wide, TeamId(2)), UNLABELLED_TEAM);
- assert_eq!(
- &*team_label(&TeamAllowlist::All, TeamId(2)),
- UNLABELLED_TEAM
- );
- assert_eq!(
- &*team_label(
- &"".parse::<TeamAllowlist>().expect("blank parses"),
- TeamId(2)
- ),
- UNLABELLED_TEAM
- );
- }
-}
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index 8abc991322f4..c23b02b85130 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -2,6 +2,8 @@
//! 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::sync::Arc;
+
use chrono::Utc;
use chrono_tz::Tz;
use clickhouse::query::RowCursor;
@@ -10,6 +12,7 @@ use cohort_core::day_idx_in_tz;
use cohort_core::events::CohortStreamEvent;
use cohort_core::filters::TeamId;
use cohort_core::hogvm::VmErrorClass;
+use common_types::cohort::TeamAllowlist;
use metrics::{counter, histogram};
use tokio_util::sync::CancellationToken;
use tracing::info;
@@ -19,35 +22,46 @@ use super::row::{row_to_event, EventRow};
use super::scan_volume::{self, ScanKind};
use super::sql::{plan_scan, scan_sql, ScanPlan};
use crate::domain::{
- conditions_active_on, ActiveConditions, AggregateError, CancelCause, ChunkAccumulator,
- ChunkDomainError, ClaimedChunk, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun,
- RecordOutcome, RecordStats, ScanVolume, ScannedChunk, SeedDomain, SeedTile, UtcMillis,
+ conditions_active_on, ActiveConditions, AggregateError, BlobSource, CancelCause,
+ ChunkAccumulator, ChunkDomainError, ChunkProjection, ClaimedChunk, ConditionAnalyses, DayIdx,
+ EventNameSet, Halted, PinnedCondition, PinnedRun, RecordOutcome, RecordStats, ScanVolume,
+ ScannedChunk, SeedDomain, SeedTile, UtcMillis,
};
use crate::observability::metrics::{
- MetricTimer, AGGREGATE_ENTRIES, CHUNKS_VACUOUS, CHUNK_SCAN_DURATION_SECONDS,
- CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS, ROWS_SCANNED,
+ team_label, MetricTimer, AGGREGATE_ENTRIES, CHUNKS_PROJECTED, CHUNKS_VACUOUS,
+ CHUNK_SCAN_DURATION_SECONDS, CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS,
+ PROJECTION_KEYS, ROWS_SCANNED,
};
#[derive(Clone)]
pub struct ChunkScanner {
client: clickhouse::Client,
+ /// Only what bounds the `team_id` label on the projection metrics. The scanner makes no
+ /// admission decision from it — discovery already did, and re-deciding here would give one
+ /// chunk a second, quieter place to be dropped.
+ allowlist: TeamAllowlist,
}
impl ChunkScanner {
- pub fn new(client: clickhouse::Client) -> Self {
- Self { client }
+ pub fn new(client: clickhouse::Client, allowlist: TeamAllowlist) -> Self {
+ Self { client, allowlist }
}
+ /// `analyses` is the run's, not the chunk's: it is a pure function of the pinned bytecode, so
+ /// every chunk of a run — and every retry of one, on any replica — narrows from the same answer.
+ /// Only [`ConditionAnalyses::projection`] is per chunk, over the conditions active on its day.
pub async fn scan(
&self,
chunk: ClaimedChunk,
run: &PinnedRun,
+ analyses: &ConditionAnalyses,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
) -> Result<ScannedChunk, Halted<ClaimedChunk, ScanError>> {
self.scan_at(
chunk,
run,
+ analyses,
Utc::now().timestamp_millis(),
lease_cancel,
shutdown,
@@ -59,12 +73,13 @@ impl ChunkScanner {
&self,
chunk: ClaimedChunk,
run: &PinnedRun,
+ analyses: &ConditionAnalyses,
now_ms: i64,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
) -> Result<ScannedChunk, Halted<ClaimedChunk, ScanError>> {
match self
- .scan_tiles(&chunk, run, now_ms, lease_cancel, shutdown)
+ .scan_tiles(&chunk, run, analyses, now_ms, lease_cancel, shutdown)
.await
{
Ok((tiles, volume)) => Ok(chunk.into_scanned(tiles, volume)),
@@ -77,6 +92,7 @@ impl ChunkScanner {
&self,
chunk: &ClaimedChunk,
run: &PinnedRun,
+ analyses: &ConditionAnalyses,
now_ms: i64,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
@@ -102,10 +118,12 @@ impl ChunkScanner {
return Ok((Vec::new(), ScanVolume::default()));
}
};
+ let projection = analyses.projection(&active);
+ self.record_projection(run.team_id, &projection);
let mut cursor = self
.client
- .query(&scan_sql(&scan_spec))
+ .query(&scan_sql(&scan_spec, &projection))
.with_option(
LOG_COMMENT_OPTION,
ScanLogComment::BehavioralChunk {
@@ -139,6 +157,38 @@ impl ChunkScanner {
let tiles = accumulator.into_tiles(&domain, run.run_id, spec.lease.epoch());
Ok((tiles, volume))
}
+
+ /// 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) {
+ let team = team_label(&self.allowlist, team_id);
+ counter!(
+ CHUNKS_PROJECTED,
+ "outcome" => projection.outcome(),
+ "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),
+ ] {
+ record_projected_keys(blob, source, team.clone());
+ }
+ }
+}
+
+/// 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(),
+ };
+ histogram!(PROJECTION_KEYS, "blob" => blob, "team_id" => team).record(keys as f64);
}
/// Whether the cursor yielded anything, which is what separates a chunk with no matching history
@@ -315,7 +365,8 @@ mod tests {
use super::*;
use crate::domain::{
- plan_days, Boundary, ClaimEpoch, ConditionHash, Lookback, PlanCaps, RunId, SChunkMs,
+ plan_days, Boundary, ClaimEpoch, ColumnPlan, ConditionHash, Lookback, PlanCaps,
+ ProjectedKeys, RunId, SChunkMs, ScalarColumn,
};
const HASH: &str = "aaaaaaaaaaaaaaaa";
@@ -420,6 +471,75 @@ mod tests {
assert_eq!(tiles[0].count(), 1);
}
+ /// 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
+ /// unread one takes a `0`, and the outcome label follows the arm.
+ ///
+ /// The recorder here is a plain one, not the configured one — which ladder
+ /// [`PROJECTION_KEYS`] renders under is `observability::metrics`'s question, and answering it
+ /// twice would let the two answers drift.
+ #[test]
+ fn the_projection_metrics_report_each_blob_by_its_own_rule() {
+ let scanner = ChunkScanner::new(
+ clickhouse::Client::default(),
+ TeamAllowlist::Only(std::collections::HashSet::from([2])),
+ );
+ let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
+ let handle = recorder.handle();
+ metrics::with_local_recorder(&recorder, || {
+ scanner.record_projection(
+ 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,
+ }),
+ );
+ scanner.record_projection(TeamId(2), &ChunkProjection::FullColumns);
+ });
+ let rendered = handle.render();
+
+ for outcome in ["projected", "full_columns"] {
+ assert!(
+ rendered.contains(&format!(
+ "{CHUNKS_PROJECTED}{{outcome=\"{outcome}\",team_id=\"2\"}} 1"
+ )),
+ "{outcome} chunk was not counted under its own label:\n{rendered}"
+ );
+ }
+ // Two keys read, and one blob read at nothing — the reading the whole change exists for.
+ assert!(
+ rendered.contains(&format!(
+ "{PROJECTION_KEYS}_sum{{blob=\"properties\",team_id=\"2\"}} 2"
+ )),
+ "the kept-key count is not the number of keys:\n{rendered}"
+ );
+ assert!(
+ rendered.contains(&format!(
+ "{PROJECTION_KEYS}_sum{{blob=\"person_properties\",team_id=\"2\"}} 0"
+ )),
+ "an unread blob did not record a zero:\n{rendered}"
+ );
+ // The wide chunk's blobs take no sample, so the two series hold one reading each rather
+ // than a sentinel that a dashboard would average in as a real key count.
+ for blob in ["properties", "person_properties"] {
+ assert!(
+ rendered.contains(&format!(
+ "{PROJECTION_KEYS}_count{{blob=\"{blob}\",team_id=\"2\"}} 1"
+ )),
+ "{blob} took a sample from the full-columns chunk:\n{rendered}"
+ );
+ }
+ }
+
#[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.rs
index 71f2401a1808..8470f0cfc499 100644
--- a/rust/cohort-seeder/src/clickhouse/sql.rs
+++ b/rust/cohort-seeder/src/clickhouse/sql.rs
@@ -5,7 +5,10 @@ use std::num::NonZeroU32;
use cohort_core::filters::TeamId;
-use crate::domain::{BandSpec, EventNameSet, SeedDomain};
+use crate::domain::{
+ BandSpec, BlobSource, ChunkProjection, ColumnPlan, EventNameSet, ProjectedKeys, ScalarColumn,
+ SeedDomain,
+};
/// The rendered scan's inputs, proven complete: constructed only by [`plan_scan`] from already-proven
/// types, so [`scan_sql`] never re-validates. Fields stay private — the SQL text is the only output.
@@ -51,7 +54,20 @@ pub fn plan_scan(
})
}
-pub fn scan_sql(spec: &ScanSpec) -> String {
+/// Render one chunk's scan.
+///
+/// The projection is a separate parameter rather than a [`ScanSpec`] field: the spec is what
+/// `plan_scan` proved about the chunk's range and event names, while the projection is derived from
+/// the conditions active on it. Keeping them apart lets one spec render both forms, which is what
+/// the shadow compare needs to scan the same rows twice.
+///
+/// The column list is the same eight columns in the same order whatever the projection, so the row
+/// decoder's positional read never has to know which arm ran.
+pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {
+ let select_list = match projection {
+ ChunkProjection::FullColumns => render_select_list(&ColumnPlan::full()),
+ ChunkProjection::Projected(plan) => render_select_list(plan),
+ };
let event_names = spec
.event_names
.iter()
@@ -68,7 +84,8 @@ pub fn scan_sql(spec: &ScanSpec) -> String {
};
format!(
- "SELECT toString(e.uuid) AS uuid, e.event, e.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 e.person_properties, e.elements_chain\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 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_list,
spec.team_id.0,
spec.team_id.0,
spec.day_start_ms,
@@ -79,6 +96,80 @@ pub fn scan_sql(spec: &ScanSpec) -> String {
)
}
+/// The eight-column select list. `event`, `timestamp`, `distinct_id`, and the override-resolved
+/// `person_id` are always selected: the fold places the row in its day by timestamp, the accumulator
+/// keys on the person, and the event name decides which conditions run.
+fn render_select_list(plan: &ColumnPlan) -> String {
+ format!(
+ "{}, e.event, {}, 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 {}, {}",
+ match plan.uuid {
+ ScalarColumn::Keep => "toString(e.uuid) AS uuid".to_string(),
+ ScalarColumn::Empty => "'' AS uuid".to_string(),
+ },
+ render_blob("e.properties", "properties", &plan.properties),
+ render_blob(
+ "e.person_properties",
+ "person_properties",
+ &plan.person_properties
+ ),
+ match plan.elements_chain {
+ ScalarColumn::Keep => "e.elements_chain".to_string(),
+ ScalarColumn::Empty => "'' AS elements_chain".to_string(),
+ },
+ )
+}
+
+/// 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.
+///
+/// Not parsing is also a behavior change, and it is the reason [`BlobSource::Empty`] is not just a
+/// cheaper [`BlobSource::Keys`]. A row whose blob is malformed fails the globals build today and
+/// is dropped as a skipped row. Once the column is an empty literal there is nothing to parse, so
+/// the same row evaluates on its other globals. The live processor still parses the whole Kafka
+/// payload and still drops it, so a seeded history counts events live evaluation never will. This
+/// is the same class of over-count as the deep-nesting divergence pinned in
+/// `tests/ch_rebuild_equivalence.rs`, and it is wider: it covers every malformed blob, not only
+/// the ones past `serde_json`'s recursion limit. [`BlobSource::Keys`] does not share it, because
+/// the rebuild passes a non-object through verbatim and the parse fails exactly as before.
+fn render_blob(column: &str, alias: &str, source: &BlobSource) -> String {
+ match source {
+ BlobSource::Full => column.to_string(),
+ BlobSource::Empty => format!("'' AS {alias}"),
+ BlobSource::Keys(keys) => format!("{} AS {alias}", rebuild_expr(column, keys)),
+ }
+}
+
+/// Rebuild a JSON object from its top-level entries, keeping only `keys` and their values.
+///
+/// Not byte-identical to the original: `JSONExtractKeysAndValuesRaw` re-serializes what it
+/// extracts, recursively, so string escapes are decoded and re-escaped and float-variant numbers
+/// re-print shortest-form (`1.0` to `1`, `1e3` to `1000`). Integer digits survive exactly. The
+/// materialized `mat_*` columns cannot even promise that much, because they strip quotes, so a
+/// string and a number become indistinguishable.
+///
+/// The float re-print is only safe once HogVM compares numbers numerically. Until then `Num`
+/// equality is variant-exact, so `Float(100.0)` and `Integer(100)` are different values, and a
+/// re-printed token flips any condition that compares against a whole number: `== 100` starts
+/// matching a row it missed, and `!= 100` stops matching one it caught. So this rebuild must not
+/// reach production before that change does. The `ch_rebuild_equivalence` corpus encodes the
+/// post-change semantics, which is what its oracle blurs.
+///
+/// Anything that is not a JSON object passes through verbatim: malformed text, non-object roots,
+/// and any document holding a number ClickHouse cannot represent. `JSONType` reports `Null` for
+/// them all, and the untouched blob then reaches the same parse, or the same parse failure and
+/// skipped-row metric, it reaches today.
+pub fn rebuild_expr(column: &str, keys: &ProjectedKeys) -> String {
+ let key_list = keys
+ .iter()
+ .map(clickhouse_string_literal)
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!(
+ "if(JSONType({column}) != 'Object', {column}, concat('{{', arrayStringConcat(arrayMap(kv -> concat(toJSONString(kv.1), ':', kv.2), arrayFilter(kv -> kv.1 IN ({key_list}), JSONExtractKeysAndValuesRaw({column}))), ','), '}}'))"
+ )
+}
+
fn clickhouse_string_literal(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('\'');
@@ -115,11 +206,42 @@ fn clickhouse_string_literal(value: &str) -> String {
#[cfg(test)]
mod tests {
+ use std::collections::BTreeSet;
+
use chrono_tz::UTC;
use super::*;
use crate::domain::{Boundary, SChunkMs, SeedDomain, UtcMillis};
+ /// The rendered scan for a spec, wide.
+ fn full_sql(spec: &ScanSpec) -> String {
+ scan_sql(spec, &ChunkProjection::FullColumns)
+ }
+
+ fn keys(names: &[&str]) -> ProjectedKeys {
+ ProjectedKeys::new(
+ names
+ .iter()
+ .map(|name| (*name).to_owned())
+ .collect::<BTreeSet<_>>(),
+ )
+ .expect("the test key sets are non-empty")
+ }
+
+ /// The three wide goldens pin the whole query, so the projected cases assert only the part that
+ /// varies. Extracted rather than re-rendered, so a change to the surrounding SQL cannot slip
+ /// past by matching on a substring the test built the same way the code did.
+ fn select_list_of(sql: &str) -> &str {
+ sql.strip_prefix("SELECT ")
+ .and_then(|rest| rest.split_once("\nFROM events AS e"))
+ .map(|(select_list, _)| select_list)
+ .expect("every rendered scan opens with its select list")
+ }
+
+ fn unbanded_spec() -> ScanSpec {
+ spec(vec!["purchase".to_string()], BandSpec::new(0, 1).unwrap())
+ }
+
fn domain() -> SeedDomain {
SeedDomain::new(
1,
@@ -144,7 +266,7 @@ mod tests {
BandSpec::new(0, 1).unwrap(),
);
assert_eq!(
- scan_sql(&spec),
+ full_sql(&spec),
"SELECT toString(e.uuid) AS uuid, e.event, e.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 e.person_properties, e.elements_chain\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 = 2\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 = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('$pageview', 'purchase')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)"
);
}
@@ -153,7 +275,7 @@ mod tests {
fn banded_scan_sql_hashes_the_resolved_person() {
let spec = spec(vec!["purchase".to_string()], BandSpec::new(3, 8).unwrap());
assert_eq!(
- scan_sql(&spec),
+ full_sql(&spec),
"SELECT toString(e.uuid) AS uuid, e.event, e.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 e.person_properties, e.elements_chain\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 = 2\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 = 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 cityHash64(toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)))\n % 8 = 3"
);
}
@@ -168,7 +290,7 @@ mod tests {
BandSpec::new(0, 1).unwrap(),
);
assert_eq!(
- scan_sql(&spec),
+ full_sql(&spec),
"SELECT toString(e.uuid) AS uuid, e.event, e.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 e.person_properties, e.elements_chain\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 = 2\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 = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('quote\\' OR 1 = 1 --', 'slash\\\\name\\nnext')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)"
);
}
@@ -183,7 +305,7 @@ mod tests {
vec!["converted?".to_string(), "why?fields".to_string()],
BandSpec::new(0, 1).unwrap(),
);
- let sql = scan_sql(&spec);
+ let sql = full_sql(&spec);
assert!(sql.contains("e.event IN ('converted??', 'why??fields')"));
let unescaped_placeholders = sql
.char_indices()
@@ -194,4 +316,98 @@ mod tests {
.count();
assert_eq!(unescaped_placeholders, 0, "a lone `?` survived escaping");
}
+
+ /// A chunk whose conditions read nothing but the always-kept columns. Every narrowable column
+ /// becomes an empty literal, so ClickHouse reads none of them — this is the shape the whole
+ /// change exists to produce.
+ #[test]
+ fn a_chunk_reading_no_narrowable_column_selects_four_empty_literals() {
+ let projection = ChunkProjection::Projected(ColumnPlan {
+ uuid: ScalarColumn::Empty,
+ elements_chain: ScalarColumn::Empty,
+ properties: BlobSource::Empty,
+ person_properties: BlobSource::Empty,
+ });
+ assert_eq!(
+ select_list_of(&scan_sql(&unbanded_spec(), &projection)),
+ "'' AS uuid, e.event, '' 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"
+ );
+ }
+
+ /// The mixed shape production will mostly render: one blob rebuilt from named keys, the other
+ /// needed whole because some condition hands the object somewhere.
+ #[test]
+ fn a_mixed_plan_rebuilds_one_blob_and_keeps_the_other_whole() {
+ let projection = ChunkProjection::Projected(ColumnPlan {
+ uuid: ScalarColumn::Keep,
+ elements_chain: ScalarColumn::Empty,
+ properties: BlobSource::Keys(keys(&["plan", "utm_source"])),
+ person_properties: BlobSource::Full,
+ });
+ assert_eq!(
+ select_list_of(&scan_sql(&unbanded_spec(), &projection)),
+ "toString(e.uuid) AS uuid, e.event, if(JSONType(e.properties) != 'Object', e.properties, concat('{', arrayStringConcat(arrayMap(kv -> concat(toJSONString(kv.1), ':', kv.2), arrayFilter(kv -> kv.1 IN ('plan', 'utm_source'), JSONExtractKeysAndValuesRaw(e.properties))), ','), '}')) 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 e.person_properties, '' AS elements_chain"
+ );
+ }
+
+ /// The mirror image, which is what proves each blob rebuilds from its own column under its own
+ /// alias. A rebuild that read `e.properties` for both, or aliased both as `properties`, still
+ /// matches the case above and its golden.
+ #[test]
+ fn the_person_blob_rebuilds_from_its_own_column_and_alias() {
+ let projection = ChunkProjection::Projected(ColumnPlan {
+ uuid: ScalarColumn::Keep,
+ elements_chain: ScalarColumn::Empty,
+ properties: BlobSource::Full,
+ person_properties: BlobSource::Keys(keys(&["email", "plan"])),
+ });
+ assert_eq!(
+ select_list_of(&scan_sql(&unbanded_spec(), &projection)),
+ "toString(e.uuid) AS uuid, e.event, e.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 if(JSONType(e.person_properties) != 'Object', e.person_properties, concat('{', arrayStringConcat(arrayMap(kv -> concat(toJSONString(kv.1), ':', kv.2), arrayFilter(kv -> kv.1 IN ('email', 'plan'), JSONExtractKeysAndValuesRaw(e.person_properties))), ','), '}')) AS person_properties, '' AS elements_chain"
+ );
+ }
+
+ /// Property keys are customer-defined, so they reach the SQL through the same escaping the
+ /// event names use — a quote would otherwise close the literal and the rest of the key would
+ /// parse as SQL. The `?` doubling matters as much here: an unescaped one never reaches
+ /// ClickHouse at all, because the client reads it as a bind placeholder and fails the query.
+ #[test]
+ fn projected_keys_are_escaped_like_every_other_literal() {
+ let projection = ChunkProjection::Projected(ColumnPlan {
+ uuid: ScalarColumn::Empty,
+ elements_chain: ScalarColumn::Keep,
+ properties: BlobSource::Keys(keys(&[
+ "quote' OR 1 = 1 --",
+ "slash\\key\nnext",
+ "converted?",
+ "$feature/flag",
+ ])),
+ person_properties: BlobSource::Empty,
+ });
+ let sql = scan_sql(&unbanded_spec(), &projection);
+ assert!(
+ sql.contains(
+ "kv.1 IN ('$feature/flag', 'converted??', 'quote\\' OR 1 = 1 --', 'slash\\\\key\\nnext')"
+ ),
+ "{sql}"
+ );
+ assert_eq!(
+ select_list_of(&sql).matches("'' AS uuid").count(),
+ 1,
+ "{sql}"
+ );
+ assert!(select_list_of(&sql).ends_with("e.elements_chain"), "{sql}");
+ }
+
+ /// The wide arm and the plan that keeps every column render the same text, which is what makes
+ /// the frozen strings above a contract over both. Without this, the fallback could drift into a
+ /// second, untested spelling of today's scan.
+ #[test]
+ fn the_full_columns_arm_renders_exactly_the_all_columns_plan() {
+ let spec = unbanded_spec();
+ assert_eq!(
+ scan_sql(&spec, &ChunkProjection::FullColumns),
+ scan_sql(&spec, &ChunkProjection::Projected(ColumnPlan::full()))
+ );
+ }
}
diff --git a/rust/cohort-seeder/src/domain/condition_analysis.rs b/rust/cohort-seeder/src/domain/condition_analysis.rs
index 940d3990963b..1890d5e41261 100644
--- a/rust/cohort-seeder/src/domain/condition_analysis.rs
+++ b/rust/cohort-seeder/src/domain/condition_analysis.rs
@@ -1,8 +1,10 @@
-//! Domain layer: the static analysis of a run's pinned conditions, and the census over it.
-//! Depends on `condition`, `ids`, and `cohort-core`.
+//! Domain layer: the static analysis of a run's pinned conditions, the census over it, and the
+//! per-chunk projection derived from it. Depends on `condition`, `ids`, `plan`, `projection`, and
+//! `cohort-core`.
//!
-//! Nothing in the scan path consumes the analysis yet: it is published as counters and one log line
-//! per run, so the shape of real catalogs is known before anything is built on it.
+//! Two consumers read the same analysis. The scan path narrows each chunk's SELECT through
+//! [`ConditionAnalyses::projection`]; the census reports per run what real catalogs look like, which
+//! is what says whether the narrowing can pay on a given team's event mix.
//!
//! The census is shaped around the question a later projection pass has to answer, which is
//! per event name rather than per condition. A scan selects columns for a whole event, so one
@@ -26,6 +28,8 @@ use cohort_core::hogvm::analysis::{
use super::condition::PinnedCondition;
use super::ids::ConditionHash;
+use super::plan::ActiveConditions;
+use super::projection::ChunkProjection;
/// What one condition turned out to need. Ordered so a census renders the same way every time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@@ -76,9 +80,9 @@ impl ConditionClass {
(EvaluationClass::EventOnly { .. }, Projection::FullColumns(reason))
| (EvaluationClass::General, Projection::FullColumns(reason)) => match reason {
FullColumnsReason::Unanalyzable(_) => Self::Unanalyzable,
- FullColumnsReason::BarePropertiesRoot | FullColumnsReason::BarePersonRoot => {
- Self::FullColumns
- }
+ FullColumnsReason::BarePropertiesRoot
+ | FullColumnsReason::BarePersonRoot
+ | FullColumnsReason::RepresentationSensitiveCall => Self::FullColumns,
},
(EvaluationClass::General, Projection::Reads(_)) => Self::Projectable,
}
@@ -143,6 +147,16 @@ impl ConditionAnalyses {
Self { by_hash }
}
+ /// What a scan over the conditions active on one chunk has to select.
+ ///
+ /// Takes the active set rather than the run's whole condition list: a window that has slid past
+ /// the chunk's day contributes nothing to that chunk's evaluation, so widening the scan for it
+ /// would read columns no condition on that day reads. An active hash with no analysis fails
+ /// closed inside [`ChunkProjection::derive`].
+ pub fn projection(&self, active: &ActiveConditions) -> ChunkProjection {
+ ChunkProjection::derive(active.iter().map(|hash| self.by_hash.get(hash)))
+ }
+
/// Count the conditions by class, and account for each event name what a projection over it
/// would have to supply.
///
@@ -386,7 +400,7 @@ mod tests {
use serde_json::json;
use super::*;
- use crate::domain::Lookback;
+ use crate::domain::{BlobSource, Lookback};
fn hash(value: &str) -> ConditionHash {
ConditionHash::parse(value).expect("test hashes are 16 ASCII bytes")
@@ -690,6 +704,44 @@ mod tests {
assert_eq!(census.render_reads(), "");
}
+ /// A chunk's projection is derived from the conditions active on its day, not from the run's
+ /// whole list. A window that has slid past the day cannot affect its evaluation, so the wide
+ /// read of a condition outside it must not cost that chunk its narrow scan.
+ #[test]
+ fn a_chunks_projection_ignores_conditions_that_are_not_active_on_it() {
+ let conditions = [
+ condition("narrow0000000000", "signup"),
+ condition("wide000000000000", "checkout"),
+ ];
+ let catalog = filters(&[
+ ("narrow0000000000", "signup", property_condition()),
+ ("wide000000000000", "checkout", bare_properties()),
+ ]);
+ let analyses = ConditionAnalyses::build(&conditions, &catalog);
+
+ let narrow_only = ActiveConditions::new([hash("narrow0000000000")]);
+ let ChunkProjection::Projected(plan) = analyses.projection(&narrow_only) else {
+ panic!("the narrow condition alone must project");
+ };
+ match &plan.properties {
+ BlobSource::Keys(keys) => assert_eq!(keys.iter().collect::<Vec<_>>(), ["plan"]),
+ other => panic!("expected key-filtered properties, got {other:?}"),
+ }
+
+ let both = ActiveConditions::new([hash("narrow0000000000"), hash("wide000000000000")]);
+ assert_eq!(analyses.projection(&both), ChunkProjection::FullColumns);
+ }
+
+ /// 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]
+ fn an_active_hash_without_an_analysis_projects_full_columns() {
+ let conditions = [condition("nobytecode000000", "purchase")];
+ let analyses = ConditionAnalyses::build(&conditions, &filters(&[]));
+ let active = ActiveConditions::new([hash("nobytecode000000")]);
+ assert_eq!(analyses.projection(&active), ChunkProjection::FullColumns);
+ }
+
#[test]
fn a_run_with_no_conditions_reports_an_empty_census() {
let census = ConditionAnalyses::default().census(&[]);
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 85e3ede53263..9f1aed65ce08 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -19,6 +19,7 @@ pub mod partition;
pub mod person;
pub mod pinned;
pub mod plan;
+pub mod projection;
pub mod window;
pub use aggregate::{
@@ -63,4 +64,5 @@ pub use pinned::{
PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,
};
pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};
+pub use projection::{BlobSource, ChunkProjection, ColumnPlan, ProjectedKeys, ScalarColumn};
pub use window::{Boundary, DomainError, PlanCaps, SeedDomain};
diff --git a/rust/cohort-seeder/src/domain/projection.rs b/rust/cohort-seeder/src/domain/projection.rs
new file mode 100644
index 000000000000..eb5f8c4235f9
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/projection.rs
@@ -0,0 +1,462 @@
+//! Domain layer: what a chunk's scan has to select, derived from the static read sets of the
+//! conditions active on it. Depends on `condition_analysis`'s inputs (`cohort-core`) only.
+//!
+//! A scan selects columns for a whole chunk, so this is a union: every active condition contributes
+//! its demands and the widest one wins. That granularity is why one condition reading a whole
+//! `properties` object costs the chunk its narrow scan, however narrow its siblings are.
+//!
+//! # Fail closed
+//!
+//! The one failure this module must not have is claiming a column the conditions turn out to need.
+//! A row scanned without it evaluates against an empty value and silently drops membership, where a
+//! column selected needlessly only costs bytes. So every arm that is not certain widens:
+//! [`Projection::FullColumns`], a hash with no analysis, a bare object root, and a path shape this
+//! mapping does not recognize all end in the wide answer.
+//!
+//! # Why the always-kept columns are absent from the types
+//!
+//! `event`, `timestamp`, `distinct_id`, and `person_id` cannot be rendered empty: the fold reads the
+//! 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 cohort_core::hogvm::analysis::{ConditionAnalysis, GlobalRoot, Projection, ReadPath};
+
+/// What one chunk's scan must select.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ChunkProjection {
+ /// Every column, which is what the seeder selected before this existed. The fail-closed arm.
+ FullColumns,
+ Projected(ColumnPlan),
+}
+
+/// The four columns a projection can narrow. The always-kept ones are deliberately absent.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ColumnPlan {
+ pub uuid: ScalarColumn,
+ pub elements_chain: ScalarColumn,
+ pub properties: BlobSource,
+ pub person_properties: BlobSource,
+}
+
+/// A column that is either selected or rendered as an empty literal. The row decoder lifts `""` to
+/// `None`, and the globals builder reads `None` as an absent value without parsing it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ScalarColumn {
+ Keep,
+ Empty,
+}
+
+/// How much of a JSON blob column the chunk needs.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum BlobSource {
+ /// The whole column, because some condition reads the object itself rather than named keys.
+ Full,
+ /// Nothing: no active condition reads under this root.
+ Empty,
+ Keys(ProjectedKeys),
+}
+
+/// 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`]
+/// already expresses more cheaply, and having two spellings of it would let a renderer choose.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProjectedKeys(BTreeSet<String>);
+
+impl ProjectedKeys {
+ /// `None` for an empty set, which [`BlobSource::Empty`] expresses instead.
+ pub fn new(keys: BTreeSet<String>) -> Option<Self> {
+ (!keys.is_empty()).then_some(Self(keys))
+ }
+
+ pub fn iter(&self) -> impl ExactSizeIterator<Item = &str> {
+ self.0.iter().map(String::as_str)
+ }
+
+ /// How many keys the rebuild keeps, always at least one. Named `count` rather than `len`
+ /// because the pair `len`/`is_empty` would advertise an emptiness this type cannot have — see
+ /// [`ProjectedKeys::new`].
+ pub fn count(&self) -> usize {
+ self.0.len()
+ }
+}
+
+impl ColumnPlan {
+ /// Every narrowable column selected whole — what the seeder scanned before this existed.
+ ///
+ /// [`ChunkProjection::FullColumns`] renders through this rather than through a second SQL
+ /// literal, so "the wide arm is byte-identical to the old scan" is a property one renderer and
+ /// its frozen tests prove, not a claim two strings have to keep agreeing on.
+ pub const fn full() -> Self {
+ Self {
+ uuid: ScalarColumn::Keep,
+ elements_chain: ScalarColumn::Keep,
+ properties: BlobSource::Full,
+ person_properties: BlobSource::Full,
+ }
+ }
+}
+
+impl ChunkProjection {
+ /// Derive the union projection from one analysis per active condition, `None` where the frozen
+ /// catalog carried no bytecode for that condition's hash.
+ ///
+ /// Pure and deterministic over the pinned payload, so a chunk retried on another replica — or
+ /// scanned twice by the shadow compare — derives the identical projection.
+ pub fn derive<'a>(analyses: impl IntoIterator<Item = Option<&'a ConditionAnalysis>>) -> Self {
+ let mut demand = Demand::default();
+ for analysis in analyses {
+ // A condition that never reached the analyzer is a condition whose reads are unknown.
+ let Some(analysis) = analysis else {
+ return Self::FullColumns;
+ };
+ match &analysis.projection {
+ Projection::FullColumns(_) => return Self::FullColumns,
+ Projection::Reads(paths) => {
+ for path in paths {
+ demand.add(path);
+ }
+ }
+ }
+ }
+ Self::Projected(demand.into_plan())
+ }
+
+ /// The label this chunk's scan is metered under.
+ pub const fn outcome(&self) -> &'static str {
+ match self {
+ Self::FullColumns => "full_columns",
+ Self::Projected(_) => "projected",
+ }
+ }
+}
+
+/// The accumulating union, before it is frozen into a [`ColumnPlan`]. Separate from the plan so the
+/// plan has no half-built state: a `BlobDemand::Keys` that is still empty is representable here and
+/// not there.
+#[derive(Debug, Default)]
+struct Demand {
+ uuid: bool,
+ elements_chain: bool,
+ properties: BlobDemand,
+ person_properties: BlobDemand,
+}
+
+/// How much of a blob the conditions seen so far need. Ordered by width: `Whole` absorbs `Keys`,
+/// which absorbs `Nothing`.
+#[derive(Debug, Default)]
+enum BlobDemand {
+ #[default]
+ Nothing,
+ Keys(BTreeSet<String>),
+ Whole,
+}
+
+impl BlobDemand {
+ fn widen_to_whole(&mut self) {
+ *self = Self::Whole;
+ }
+
+ fn add_key(&mut self, key: &str) {
+ match self {
+ Self::Whole => {}
+ Self::Nothing => *self = Self::Keys(BTreeSet::from([key.to_owned()])),
+ Self::Keys(keys) => {
+ keys.insert(key.to_owned());
+ }
+ }
+ }
+
+ fn freeze(self) -> BlobSource {
+ match self {
+ Self::Whole => BlobSource::Full,
+ Self::Nothing => BlobSource::Empty,
+ Self::Keys(keys) => {
+ ProjectedKeys::new(keys).map_or(BlobSource::Empty, BlobSource::Keys)
+ }
+ }
+ }
+}
+
+impl Demand {
+ /// Record what one read path needs. Exhaustive over [`GlobalRoot`], so a root added to the
+ /// globals has to decide here rather than fall into a default that might be too narrow.
+ fn add(&mut self, path: &ReadPath) {
+ match path.root {
+ GlobalRoot::Uuid => self.uuid = true,
+ // The analyzer records `properties.$elements_chain` as its own path whenever a program
+ // reads `elements_chain`, so the fallback the globals builder applies is already
+ // covered by the `Properties` arm. Claiming it again here would say the same thing
+ // twice.
+ GlobalRoot::ElementsChain => self.elements_chain = true,
+ GlobalRoot::Properties => match path.segments.first() {
+ // A nested path needs its root key's raw value, which carries the whole subtree.
+ Some(key) => self.properties.add_key(key),
+ // The analyzer reports a bare `properties` as a full-columns reason rather than a
+ // read, so this is unreachable; widening keeps it harmless if that ever changes.
+ None => self.properties.widen_to_whole(),
+ },
+ GlobalRoot::Person => self.add_person(&path.segments),
+ GlobalRoot::Pdi => match path.segments.first().map(String::as_str) {
+ Some("distinct_id" | "person_id") => {}
+ Some("person") => self.add_person(&path.segments[1..]),
+ _ => self.person_properties.widen_to_whole(),
+ },
+ // Decided by columns no projection can drop, or by values the globals synthesize the
+ // same way for every row: the elements-chain siblings are constants, `$group_n` is
+ // null, `group_n` is an empty property bag, and `variables` is an empty object.
+ GlobalRoot::Event
+ | GlobalRoot::Timestamp
+ | GlobalRoot::DistinctId
+ | GlobalRoot::ElementsChainHref
+ | GlobalRoot::ElementsChainTexts
+ | GlobalRoot::ElementsChainIds
+ | GlobalRoot::ElementsChainElements
+ | GlobalRoot::DollarGroup(_)
+ | GlobalRoot::Group(_)
+ | GlobalRoot::Variables => {}
+ }
+ }
+
+ /// The `{ id, properties }` object, reached either as `person` or as `pdi.person`.
+ fn add_person(&mut self, segments: &[String]) {
+ let mut segments = segments.iter().map(String::as_str);
+ match (segments.next(), segments.next()) {
+ // `person.id` is the resolved person, which the scan always selects.
+ (Some("id"), _) => {}
+ (Some("properties"), Some(key)) => self.person_properties.add_key(key),
+ // A bare `person` or `person.properties` hands a whole object somewhere, and any other
+ // key resolves to null on every row — but telling those two apart is exactly the
+ // judgement this module does not make.
+ _ => self.person_properties.widen_to_whole(),
+ }
+ }
+
+ fn into_plan(self) -> ColumnPlan {
+ ColumnPlan {
+ uuid: keep_if(self.uuid),
+ elements_chain: keep_if(self.elements_chain),
+ properties: self.properties.freeze(),
+ person_properties: self.person_properties.freeze(),
+ }
+ }
+}
+
+const fn keep_if(needed: bool) -> ScalarColumn {
+ if needed {
+ ScalarColumn::Keep
+ } else {
+ ScalarColumn::Empty
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use cohort_core::hogvm::analysis::{
+ EvaluationClass, FullColumnsReason, GroupIndex, UnanalyzableReason,
+ };
+
+ use super::*;
+
+ fn analysis(projection: Projection) -> ConditionAnalysis {
+ ConditionAnalysis {
+ evaluation: EvaluationClass::General,
+ projection,
+ }
+ }
+
+ fn reads(paths: impl IntoIterator<Item = ReadPath>) -> ConditionAnalysis {
+ analysis(Projection::Reads(paths.into_iter().collect()))
+ }
+
+ fn path(root: GlobalRoot, segments: &[&str]) -> ReadPath {
+ ReadPath::new(
+ root,
+ segments
+ .iter()
+ .map(|segment| (*segment).to_owned())
+ .collect(),
+ )
+ }
+
+ fn plan_of(analyses: &[ConditionAnalysis]) -> ColumnPlan {
+ match ChunkProjection::derive(analyses.iter().map(Some)) {
+ ChunkProjection::Projected(plan) => plan,
+ ChunkProjection::FullColumns => panic!("expected a projected plan"),
+ }
+ }
+
+ fn keys(source: &BlobSource) -> Vec<&str> {
+ match source {
+ BlobSource::Keys(keys) => keys.iter().collect(),
+ other => panic!("expected key-filtered blob, got {other:?}"),
+ }
+ }
+
+ /// The empty plan: a condition that reads nothing needs none of the four narrowable columns.
+ /// Every one of them rendered empty is what makes an event-only chunk cheap, so this is the
+ /// case that pays for the whole change.
+ #[test]
+ fn a_condition_reading_only_always_kept_globals_needs_no_narrowable_column() {
+ let plan = plan_of(&[reads([
+ path(GlobalRoot::Event, &[]),
+ path(GlobalRoot::Timestamp, &[]),
+ path(GlobalRoot::DistinctId, &[]),
+ path(GlobalRoot::Person, &["id"]),
+ path(GlobalRoot::Pdi, &["person_id"]),
+ path(GlobalRoot::Pdi, &["distinct_id"]),
+ path(GlobalRoot::Pdi, &["person", "id"]),
+ ])]);
+ assert_eq!(
+ plan,
+ ColumnPlan {
+ uuid: ScalarColumn::Empty,
+ elements_chain: ScalarColumn::Empty,
+ properties: BlobSource::Empty,
+ person_properties: BlobSource::Empty,
+ }
+ );
+ }
+
+ /// Constants the globals synthesize per row cost nothing: the group bags, the elements-chain
+ /// siblings, and `variables` do not come from any column. Widening on them would give back most
+ /// of the win on catalogs that use group filters.
+ #[test]
+ fn synthetic_globals_claim_no_column() {
+ let index = GroupIndex::parse(2).expect("2 is a valid group ordinal");
+ let plan = plan_of(&[reads([
+ path(GlobalRoot::Group(index), &["properties", "tier"]),
+ path(GlobalRoot::DollarGroup(index), &[]),
+ path(GlobalRoot::Variables, &["x"]),
+ path(GlobalRoot::ElementsChainHref, &[]),
+ path(GlobalRoot::ElementsChainTexts, &[]),
+ path(GlobalRoot::ElementsChainIds, &[]),
+ path(GlobalRoot::ElementsChainElements, &[]),
+ ])]);
+ assert_eq!(plan.properties, BlobSource::Empty);
+ assert_eq!(plan.person_properties, BlobSource::Empty);
+ assert_eq!(plan.uuid, ScalarColumn::Empty);
+ assert_eq!(plan.elements_chain, ScalarColumn::Empty);
+ }
+
+ /// A nested path claims its root key, because the raw value of that key carries the subtree.
+ /// Claiming the leaf instead would render a `properties` object the condition cannot index into.
+ #[test]
+ fn a_nested_property_path_claims_its_root_key() {
+ let plan = plan_of(&[reads([
+ path(GlobalRoot::Properties, &["$set", "plan", "tier"]),
+ path(GlobalRoot::Person, &["properties", "company", "size"]),
+ path(GlobalRoot::Pdi, &["person", "properties", "email"]),
+ ])]);
+ assert_eq!(keys(&plan.properties), ["$set"]);
+ assert_eq!(keys(&plan.person_properties), ["company", "email"]);
+ }
+
+ /// The union across conditions is what a chunk actually needs, deduplicated and ordered.
+ #[test]
+ fn separate_conditions_union_their_keys() {
+ let plan = plan_of(&[
+ reads([path(GlobalRoot::Properties, &["plan"])]),
+ reads([path(GlobalRoot::Properties, &["utm_source"])]),
+ reads([path(GlobalRoot::Properties, &["plan"])]),
+ ]);
+ assert_eq!(keys(&plan.properties), ["plan", "utm_source"]);
+ }
+
+ /// `person.properties` and `pdi.person` name whole objects whose keys are chosen at runtime, so
+ /// the column has to arrive intact — and a narrow sibling must not talk it back down.
+ #[test]
+ fn a_whole_object_read_widens_its_blob_and_survives_narrow_siblings() {
+ for whole in [
+ path(GlobalRoot::Person, &["properties"]),
+ path(GlobalRoot::Pdi, &["person"]),
+ ] {
+ let plan = plan_of(&[
+ reads([whole.clone()]),
+ reads([path(GlobalRoot::Person, &["properties", "email"])]),
+ ]);
+ 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:?}");
+ }
+ }
+
+ /// A key under `person` that is neither `id` nor `properties` resolves to null on every row, so
+ /// a narrow answer would even be correct. It still widens: telling those two cases apart is a
+ /// judgement this mapping does not make, and the safe direction is the wide one.
+ #[test]
+ fn an_unrecognized_person_key_widens_rather_than_guesses() {
+ for unrecognized in [
+ path(GlobalRoot::Person, &["created_at"]),
+ path(GlobalRoot::Pdi, &["person", "created_at"]),
+ path(GlobalRoot::Pdi, &["team_id"]),
+ ] {
+ let plan = plan_of(&[reads([unrecognized.clone()])]);
+ assert_eq!(
+ plan.person_properties,
+ BlobSource::Full,
+ "{unrecognized:?} did not widen"
+ );
+ }
+ }
+
+ /// An `elements_chain` read arrives from the analyzer with its `properties.$elements_chain`
+ /// fallback alongside, and both halves have to reach the scan: the globals builder reads the
+ /// property only when the column is empty, so projecting one without the other would evaluate
+ /// the condition against a chain that is not the row's.
+ #[test]
+ fn an_elements_chain_read_keeps_both_the_column_and_its_property_fallback() {
+ let plan = plan_of(&[reads([
+ path(GlobalRoot::ElementsChain, &[]),
+ path(GlobalRoot::Properties, &["$elements_chain"]),
+ ])]);
+ assert_eq!(plan.elements_chain, ScalarColumn::Keep);
+ assert_eq!(keys(&plan.properties), ["$elements_chain"]);
+ }
+
+ /// Every way a condition can escape the analysis takes the whole chunk wide, whatever its
+ /// siblings found. A narrow scan built next to one of these would drop rows.
+ #[test]
+ fn any_unnarrowable_condition_takes_the_whole_chunk_wide() {
+ let narrow = reads([path(GlobalRoot::Properties, &["plan"])]);
+ for reason in [
+ FullColumnsReason::BarePropertiesRoot,
+ FullColumnsReason::BarePersonRoot,
+ FullColumnsReason::Unanalyzable(UnanalyzableReason::DynamicGlobalPath),
+ ] {
+ let wide = analysis(Projection::FullColumns(reason.clone()));
+ assert_eq!(
+ ChunkProjection::derive([Some(&narrow), Some(&wide)]),
+ ChunkProjection::FullColumns,
+ "{reason:?}"
+ );
+ }
+ // A hash the frozen catalog carried no bytecode for never reached the analyzer at all.
+ assert_eq!(
+ ChunkProjection::derive([Some(&narrow), None]),
+ ChunkProjection::FullColumns
+ );
+ }
+
+ /// No active conditions means no reads, which is the empty plan rather than the wide one.
+ #[test]
+ fn no_conditions_projects_every_narrowable_column_away() {
+ assert_eq!(
+ ChunkProjection::derive([]),
+ ChunkProjection::Projected(ColumnPlan {
+ uuid: ScalarColumn::Empty,
+ elements_chain: ScalarColumn::Empty,
+ properties: BlobSource::Empty,
+ person_properties: BlobSource::Empty,
+ })
+ );
+ }
+
+ #[test]
+ fn the_metric_outcome_names_which_arm_was_taken() {
+ assert_eq!(ChunkProjection::FullColumns.outcome(), "full_columns");
+ assert_eq!(ChunkProjection::derive([]).outcome(), "projected");
+ }
+}
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index 2267c4d3a916..20f62dd40720 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -92,7 +92,7 @@ async fn async_main(config: Config) -> Result<()> {
let pool = get_pool_with_config(&config.database_url, config.pool_config())
.context("creating cohort-seeder PostgreSQL pool")?;
let clickhouse_client = build_client(&config).context("building ClickHouse client")?;
- let scanner = ChunkScanner::new(clickhouse_client.clone());
+ let scanner = ChunkScanner::new(clickhouse_client.clone(), config.team_allowlist.clone());
let producer = SeedTileProducer::new(
&config.build_kafka_config(),
config.seed_events_topic.clone(),
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 29e52395ec27..2488deee6522 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -1,9 +1,13 @@
//! Observability leaf: the `seeder_*` metric-name constants (the seeder's metric manifest, which
-//! dashboards depend on), the shared RAII duration timer, and the Prometheus recorder installer.
-//! Depends on the metrics crates only.
+//! dashboards depend on), the shared RAII duration timer, the bounded team label every per-team
+//! series draws on, and the Prometheus recorder installer. Depends on the metrics crates plus the
+//! allowlist type the team label reads its bound from; never on another seeder module.
+use std::sync::Arc;
use std::time::{Duration, Instant};
+use cohort_core::filters::TeamId;
+use common_types::cohort::TeamAllowlist;
use metrics::histogram;
use metrics_exporter_prometheus::{BuildError, Matcher, PrometheusBuilder, PrometheusHandle};
@@ -37,6 +41,21 @@ pub const CONDITIONS_CLASSIFIED: &str = "seeder_conditions_classified_total";
/// fixable compiler template and a program nothing will ever narrow otherwise land in the same
/// `unsupported_op` bucket.
pub const CONDITIONS_UNANALYZABLE: &str = "seeder_conditions_unanalyzable_total";
+/// Behavioral chunks by whether their scan narrowed, labelled by `outcome`
+/// (`projected`/`full_columns`) and `team_id` (counter). One increment per scanned chunk.
+///
+/// `full_columns` is the fail-closed arm: at least one condition active on that chunk reads a whole
+/// object or escaped the static analysis, so the scan selects every column. A team sitting at
+/// `full_columns` is the signal to read the run's census for which event names block it.
+pub const CHUNKS_PROJECTED: &str = "seeder_chunks_projected_total";
+/// Top-level JSON keys a narrowed scan rebuilds one blob from, labelled by `blob`
+/// (`properties`/`person_properties`) and `team_id` (histogram). Zero means the blob is not read at
+/// all and the scan selects an empty literal for it.
+///
+/// A blob some condition needs whole takes no sample: there is no key count to report for it, and a
+/// sentinel would be indistinguishable from a real reading. Those show up as decoded bytes that do
+/// not fall — read this against `seeder_scan_decoded_bytes_total{kind="behavioral"}`.
+pub const PROJECTION_KEYS: &str = "seeder_projection_keys";
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";
@@ -133,6 +152,32 @@ pub const PERSON_PLANNING_DURATION_SECONDS: &str = "seeder_person_planning_durat
/// delivery separately. One name across both would compare unlike spans.
pub const PERSON_CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_person_chunk_scan_duration_seconds";
+/// How many teams a per-team series names individually before it stops naming any.
+///
+/// Sized well above the shadow rollout's team count, so the collapse is a ceiling rather than a
+/// routine truncation.
+const MAX_LABELLED_TEAMS: usize = 32;
+
+/// The label every team shares once a per-team series stops naming them.
+const UNLABELLED_TEAM: &str = "other";
+
+/// The team a metric belongs to, as a label value.
+///
+/// A team gets its own series only while `REALTIME_COHORT_TEAM_ALLOWLIST` names few enough of them.
+/// The allowlist does not bound this on its own: it accepts `all` (which a set-but-empty variable
+/// also parses to) and ranges of up to 100,000 ids, and the recorder never evicts a series, so a
+/// wide rollout would retain one per team that ever seeded. The label exists because these series
+/// answer questions about one team's catalog and scans, which a blended counter cannot; the paired
+/// log lines carry the exact team either way, so collapsing costs the dashboard, not the answer.
+pub fn team_label(allowlist: &TeamAllowlist, team_id: TeamId) -> Arc<str> {
+ match allowlist {
+ TeamAllowlist::Only(ids) if ids.len() <= MAX_LABELLED_TEAMS => {
+ Arc::from(team_id.0.to_string().as_str())
+ }
+ TeamAllowlist::Only(_) | TeamAllowlist::All => Arc::from(UNLABELLED_TEAM),
+ }
+}
+
/// Records its lifetime into `metric` on drop, so every exit — early return, halt, cancellation —
/// is sampled without a recording site per path.
pub struct MetricTimer {
@@ -213,12 +258,19 @@ const AGGREGATE_ENTRIES_BUCKETS: &[f64] = &[
10_000_000.0,
];
+/// Bucket ladder for [`PROJECTION_KEYS`], which counts JSON keys rather than seconds. The floor is
+/// 0 because "this blob is not read at all" is the reading that matters most, and the seconds ladder
+/// has no bucket that separates it from one key. The top is well above any condition set a person
+/// writes by hand, so a run reaching it means the projection has stopped narrowing anything.
+const PROJECTION_KEYS_BUCKETS: &[f64] = &[0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0];
+
/// Every seeder histogram that overrides the recorder-wide default, paired with its ladder. This is
/// the single source: [`configured_builder`] installs from it and the test iterates it, so a
/// histogram cannot be given a ladder in one place and checked against another. A histogram absent
/// from this table inherits [`DEFAULT_SECONDS_BUCKETS`], which is correct only if it measures a
/// short span in seconds.
const HISTOGRAM_LADDERS: &[(&str, &[f64])] = &[
+ (PROJECTION_KEYS, PROJECTION_KEYS_BUCKETS),
(CHUNK_SCAN_DURATION_SECONDS, SCAN_DURATION_SECONDS_BUCKETS),
(
PERSON_CHUNK_SCAN_DURATION_SECONDS,
@@ -253,7 +305,7 @@ pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
#[cfg(test)]
mod tests {
- use std::collections::HashMap;
+ use std::collections::{HashMap, HashSet};
use envconfig::Envconfig;
use metrics::histogram;
@@ -324,6 +376,32 @@ mod tests {
}
}
+ /// A blob no condition reads is the reading [`PROJECTION_KEYS`] exists to make visible, and it
+ /// is only visible while the ladder has a bucket that holds nothing else. Drop the `0` bound and
+ /// a chunk that read no keys and a chunk that read one both land in the first bucket, so the
+ /// series stops answering "is this team still projecting?" while still rendering.
+ #[test]
+ fn the_projection_key_ladder_separates_zero_keys_from_one() {
+ assert_eq!(
+ PROJECTION_KEYS_BUCKETS.first(),
+ Some(&0.0),
+ "the ladder no longer starts at 0, so an unread blob shares a bucket with a read one"
+ );
+ let recorder = configured_builder()
+ .expect("the configured bucket ladders are non-empty")
+ .build_recorder();
+ let handle = recorder.handle();
+ metrics::with_local_recorder(&recorder, || {
+ histogram!(PROJECTION_KEYS).record(0.0);
+ histogram!(PROJECTION_KEYS).record(1.0);
+ });
+ let rendered = handle.render();
+ assert!(
+ rendered.contains(&format!("{PROJECTION_KEYS}_bucket{{le=\"0\"}} 1")),
+ "the zero-key sample did not land alone in the le=0 bucket:\n{rendered}"
+ );
+ }
+
/// The person planning timer spans a ClickHouse scan and a Postgres insert, so it must not
/// share the scan ladder, whose 1.0s floor erases every sub-second planning pass. Two teams
/// apart in size have to land in different buckets for the metric to say anything.
@@ -362,4 +440,28 @@ mod tests {
"the scan ladder no longer tops out at the ClickHouse execution-time budget"
);
}
+
+ /// An allowlist that can grow with the customer base must not mint a metric series per team.
+ /// The recorder never evicts one, so a label that tracks team count leaks for the whole process
+ /// lifetime — and `all`, which a set-but-empty variable also parses to, is the configuration
+ /// the boundedness claim used to assume away.
+ #[test]
+ fn only_a_narrow_allowlist_names_teams_in_a_per_team_label() {
+ let narrow = TeamAllowlist::Only(HashSet::from([2, 7]));
+ assert_eq!(&*team_label(&narrow, TeamId(2)), "2");
+
+ let wide = TeamAllowlist::Only((0..=MAX_LABELLED_TEAMS as i32).collect());
+ assert_eq!(&*team_label(&wide, TeamId(2)), UNLABELLED_TEAM);
+ assert_eq!(
+ &*team_label(&TeamAllowlist::All, TeamId(2)),
+ UNLABELLED_TEAM
+ );
+ assert_eq!(
+ &*team_label(
+ &"".parse::<TeamAllowlist>().expect("blank parses"),
+ TeamId(2)
+ ),
+ UNLABELLED_TEAM
+ );
+ }
}
diff --git a/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs b/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs
new file mode 100644
index 000000000000..a01358ef35b1
--- /dev/null
+++ b/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs
@@ -0,0 +1,340 @@
+//! Proves against a real ClickHouse that a key-filtered blob parses to exactly what the whole blob
+//! parses to with the unread keys removed.
+//!
+//! That relation is the one new obligation the column projection takes on. Everything else about a
+//! projected row is already the pipeline it was before: the row decoder lifts an empty column to
+//! "absent" and the globals builder reads absent as `{}` without parsing, so a scan that selects
+//! fewer columns runs the unchanged hot path. Only the rebuilt blob is new text, and only
+//! ClickHouse can say what it contains.
+//!
+//! So there is no Rust mock of the rebuild expression here. A mock would prove the mock.
+//!
+//! Needs a reachable ClickHouse, which is why it sits behind `ch-test-support`. It reads its
+//! endpoint through the seeder's own `Config`/`build_client`, so it also exercises the client-side
+//! template parser that turns a bare `?` in a rendered literal into an unbound bind placeholder.
+
+#![cfg(feature = "ch-test-support")]
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use clickhouse::{Client, Row};
+use cohort_seeder::clickhouse::client::build_client;
+use cohort_seeder::clickhouse::sql::rebuild_expr;
+use cohort_seeder::config::Config;
+use cohort_seeder::domain::ProjectedKeys;
+use envconfig::Envconfig;
+use serde::Deserialize;
+use serde_json::{Map, Value};
+
+/// One blob as ClickHouse would hold it, and the keys a chunk's conditions read from it.
+struct Case {
+ blob: &'static str,
+ keys: &'static [&'static str],
+}
+
+const fn case(blob: &'static str, keys: &'static [&'static str]) -> Case {
+ Case { blob, keys }
+}
+
+/// Hand-authored rather than sampled from production: every case is here because it names a way the
+/// rebuild could differ from a prune, and a sample of real properties would carry customer data
+/// while covering none of the hostile shapes.
+const CORPUS: &[Case] = &[
+ // Ordinary shapes.
+ case(r#"{"plan":"paid","utm_source":"ads"}"#, &["plan"]),
+ case(
+ r#"{"plan":"paid","utm_source":"ads"}"#,
+ &["plan", "utm_source"],
+ ),
+ case(r#"{"plan":"paid"}"#, &["utm_source"]),
+ case(r#"{}"#, &["plan"]),
+ case(r#"{"plan":"paid"}"#, &["plan", "absent"]),
+ // Value kinds, kept raw so nothing is re-encoded on the way through.
+ case(r#"{"nested":{"a":[1,2,{"b":null}]},"x":1}"#, &["nested"]),
+ case(r#"{"list":[1,"two",false,null],"x":1}"#, &["list"]),
+ case(
+ r#"{"nul":null,"yes":true,"no":false}"#,
+ &["nul", "yes", "no"],
+ ),
+ case(r#"{"big":123456789012345678901234567890}"#, &["big"]),
+ case(
+ r#"{"tiny":-1.5e-300,"round":1.0,"zero":-0.0}"#,
+ &["tiny", "round", "zero"],
+ ),
+ // Float re-prints, and the integer tokens that must not follow them. ClickHouse re-serializes
+ // recursively, so the floats inside a kept subtree flip too, and `values_equivalent` has to
+ // recurse to read that as the same value. 64-bit integers keep their digits instead, which a
+ // condition comparing Int to Int can observe, so the oracle holds those exactly.
+ case(r#"{"exp":1e3,"caps":1E3,"x":1}"#, &["exp", "caps"]),
+ case(
+ r#"{"nested":{"round":1.0,"list":[2.0,1e3]},"x":1}"#,
+ &["nested"],
+ ),
+ case(
+ r#"{"imax":9223372036854775807,"umax":18446744073709551615}"#,
+ &["imax", "umax"],
+ ),
+ case(
+ r#"{"empty_obj":{},"empty_arr":[]}"#,
+ &["empty_obj", "empty_arr"],
+ ),
+ // Duplicate keys. ClickHouse keeps both entries in order and serde_json takes the last, so the
+ // rebuilt blob has to keep the order rather than the first match a materialized column would.
+ case(r#"{"plan":"free","plan":"paid"}"#, &["plan"]),
+ case(r#"{"plan":"free","other":1,"plan":"paid"}"#, &["plan"]),
+ case(r#"{"plan":"free","plan":"paid"}"#, &["other"]),
+ // Text realism in values.
+ case(r#"{"who":"Ana Lópe😀z","x":1}"#, &["who"]),
+ case(
+ r#"{"esc":"quote \" backslash \\ newline \n tab \t","x":1}"#,
+ &["esc"],
+ ),
+ case(r#"{"uni":"é😀","x":1}"#, &["uni"]),
+ case(r#"{"braces":"{\"not\":\"json\"}","x":1}"#, &["braces"]),
+ case(r#"{"colon":"a:b,c","x":1}"#, &["colon"]),
+ // Keys that have to survive both the SQL literal escaping and the JSON re-quoting.
+ case(r#"{"$feature/flag":"variant","x":1}"#, &["$feature/flag"]),
+ case(r#"{"has space":1,"x":2}"#, &["has space"]),
+ case(r#"{"quote\"key":1,"x":2}"#, &["quote\"key"]),
+ // The single quote is the one escape whose failure would be an injection rather than a wrong
+ // value, and the renderer's goldens can only pin the text they produce. This runs the same
+ // payload the event-name golden uses through a real server, so "the literal stays closed" is
+ // measured rather than argued.
+ case(r#"{"quote' OR 1 = 1 --":1,"x":2}"#, &["quote' OR 1 = 1 --"]),
+ case(r#"{"back\\slash":1,"x":2}"#, &["back\\slash"]),
+ case(r#"{"question?":1,"x":2}"#, &["question?"]),
+ case(r#"{"why?fields":1,"x":2}"#, &["why?fields"]),
+ case(r#"{"new\nline":1,"x":2}"#, &["new\nline"]),
+ case(r#"{"tab\tkey":1,"x":2}"#, &["tab\tkey"]),
+ case(r#"{"":1,"x":2}"#, &[""]),
+ case(r#"{"é😀":1,"x":2}"#, &["é😀"]),
+ // A key written as a JSON escape must match the decoded key a condition reads: ClickHouse
+ // decodes key escapes before the IN filter and re-encodes on the way out, and the globals a
+ // condition indexes into hold the decoded name.
+ case(r#"{"\u0070lan":"paid","x":1}"#, &["plan"]),
+ case(r#"{"\ud83d\ude00":1,"x":2}"#, &["😀"]),
+ // Case and near-miss keys must not match: a prefix match would leak a key no condition reads.
+ case(r#"{"Plan":1,"plan":2,"plan2":3}"#, &["plan"]),
+ // Roots that are valid JSON but not objects. The globals builder takes them as they are, so the
+ // rebuild has to hand them back untouched.
+ case(r#"[1,2,3]"#, &["a"]),
+ case(r#""a string""#, &["a"]),
+ case(r#"123"#, &["a"]),
+ case(r#"true"#, &["a"]),
+ case(r#"null"#, &["a"]),
+ // Malformed roots, which reach the same parse failure and the same skipped-row metric they
+ // reach today.
+ case(r#""#, &["a"]),
+ case(r#"garbage"#, &["a"]),
+ case(r#"{"a":1,"#, &["a"]),
+ case(r#"{"a":1} trailing"#, &["a"]),
+ case(r#"{"a":1}{"b":2}"#, &["a"]),
+ case(r#"{'a':1}"#, &["a"]),
+ case(r#"{"a":01}"#, &["a"]),
+ // Whitespace around a valid object is still an object to both parsers.
+ case(" \t{\"plan\":\"paid\"}\n ", &["plan"]),
+ // Many keys, few read: the shape the projection exists for.
+ case(
+ r#"{"k0":0,"k1":1,"k2":2,"k3":3,"k4":4,"k5":5,"k6":6,"k7":7,"k8":8,"k9":9,"plan":"paid"}"#,
+ &["plan", "k7"],
+ ),
+];
+
+/// What a globals build would see for one blob: the parsed value, or nothing when the parse fails
+/// and the row is skipped.
+type Parsed = Result<Value, ()>;
+
+#[derive(Row, Deserialize)]
+struct Rebuilt {
+ index: u32,
+ rebuilt: String,
+}
+
+#[tokio::test]
+async fn a_key_filtered_rebuild_parses_to_the_pruned_whole_blob() {
+ let client = connect();
+ // Grouped by key set because the key set is what the expression is rendered from, so one query
+ // per distinct set covers the whole corpus in a handful of round trips.
+ let mut by_keys: BTreeMap<&'static [&'static str], Vec<&'static str>> = BTreeMap::new();
+ for case in CORPUS {
+ by_keys.entry(case.keys).or_default().push(case.blob);
+ }
+
+ for (keys, blobs) in by_keys {
+ let rebuilt = rebuild_all(&client, keys, &blobs).await;
+ for (blob, rebuilt) in blobs.iter().zip(&rebuilt) {
+ let (rebuilt_value, pruned) = (parse(rebuilt), prune(parse(blob), keys));
+ assert!(
+ equivalent(&rebuilt_value, &pruned),
+ "blob {blob:?} filtered to {keys:?} rebuilt as {rebuilt:?}\n parsed: {rebuilt_value:?}\n wanted: {pruned:?}"
+ );
+ }
+ }
+}
+
+/// The one input class where a projected row is not the row today's pipeline produces.
+///
+/// `serde_json` refuses to parse past 128 levels of nesting while ClickHouse parses much deeper,
+/// so a blob whose *unread* part is deeper than that is skipped by the wide scan today and
+/// evaluated once projected. The live processor parses the full payload with `serde_json` and
+/// skips the same row, so this is a permanent seed-versus-live hole, not a transient seed-only
+/// one: the seeded history counts an event live evaluation never will. An over-count rather than
+/// a miss, on a shape no property editor produces. Pinned rather than hedged, because a guard
+/// would cost every row to buy back a case this names precisely.
+#[tokio::test]
+async fn a_blob_too_deep_for_serde_but_not_for_clickhouse_diverges() {
+ let deep = format!(
+ r#"{{"plan":"paid","deep":{}1{}}}"#,
+ r#"{"d":"#.repeat(200),
+ "}".repeat(200)
+ );
+ assert!(
+ parse(&deep).is_err(),
+ "the whole blob is meant to be past serde_json's recursion limit"
+ );
+
+ let client = connect();
+ let rebuilt = rebuild_all(&client, &["plan"], &[&deep]).await;
+ assert_eq!(
+ parse(&rebuilt[0]),
+ Ok(Value::Object(Map::from_iter([(
+ "plan".to_owned(),
+ Value::String("paid".to_owned())
+ )]))),
+ "the shallow key survives the rebuild, so the projected row evaluates where the wide one \
+ would have been skipped"
+ );
+}
+
+/// ClickHouse gives up on the whole document when any number token is outside what it can
+/// represent, wherever that token sits: `JSONType` reports `Null`, so the rebuild's guard passes
+/// the blob through verbatim. The projected row is then byte-identical to the wide scan's row,
+/// which is zero evaluation divergence, just wider than the pruned oracle. That is why this sits
+/// beside the depth pin instead of weakening the main assertion.
+#[tokio::test]
+async fn a_number_clickhouse_cannot_represent_passes_the_whole_blob_through() {
+ let client = connect();
+ for blob in [
+ r#"{"plan":"paid","big":123456789012345678901234567890}"#,
+ r#"{"plan":"paid","huge":1e309}"#,
+ ] {
+ let rebuilt = rebuild_all(&client, &["plan"], &[blob]).await;
+ assert_eq!(rebuilt[0], blob, "expected verbatim passthrough");
+ }
+}
+
+fn connect() -> Client {
+ let config = Config::init_from_env().expect("the seeder config falls back to its defaults");
+ build_client(&config).expect("the default ClickHouse client builds")
+}
+
+/// Run the production rebuild expression over `blobs`, in the blobs' own order.
+async fn rebuild_all(client: &Client, keys: &[&str], blobs: &[&str]) -> Vec<String> {
+ let keys = ProjectedKeys::new(keys.iter().map(|key| (*key).to_owned()).collect())
+ .expect("every corpus case names at least one key");
+ let sql = format!(
+ "WITH ? AS blobs\nSELECT index, {} AS rebuilt\nFROM (SELECT arrayJoin(arrayEnumerate(blobs)) AS index, blobs[index] AS blob)\nORDER BY index",
+ rebuild_expr("blob", &keys)
+ );
+ let owned = blobs
+ .iter()
+ .map(|blob| (*blob).to_owned())
+ .collect::<Vec<_>>();
+ let rows = client
+ .query(&sql)
+ .bind(owned)
+ .fetch_all::<Rebuilt>()
+ .await
+ .unwrap_or_else(|error| panic!("the rebuild query failed: {error}\n{sql}"));
+ assert_eq!(rows.len(), blobs.len(), "a blob went missing: {sql}");
+ // `arrayEnumerate` is 1-based, and the caller pairs these rows with its blobs positionally, so
+ // the order the query promises has to hold before the results are stripped down to strings.
+ for (position, row) in rows.iter().enumerate() {
+ assert_eq!(
+ row.index as usize,
+ position + 1,
+ "rows arrived out of order: {sql}"
+ );
+ }
+ rows.into_iter().map(|row| row.rebuilt).collect()
+}
+
+/// What the globals builder would get from a raw column value.
+fn parse(blob: &str) -> Parsed {
+ serde_json::from_str(blob).map_err(|_| ())
+}
+
+/// The whole blob's parse with everything the chunk does not read removed — the value a projected
+/// row has to reproduce. Non-objects pass through, because a projection cannot narrow what has no
+/// keys.
+fn prune(parsed: Parsed, keys: &[&str]) -> Parsed {
+ let keys = keys.iter().copied().collect::<BTreeSet<_>>();
+ parsed.map(|value| match value {
+ Value::Object(map) => Value::Object(
+ map.into_iter()
+ .filter(|(key, _)| keys.contains(key.as_str()))
+ .collect(),
+ ),
+ other => other,
+ })
+}
+
+fn equivalent(a: &Parsed, b: &Parsed) -> bool {
+ match (a, b) {
+ (Ok(a), Ok(b)) => values_equivalent(a, b),
+ _ => a == b,
+ }
+}
+
+/// Equal under everything the evaluator can observe once HogVM compares numbers numerically: a
+/// float ClickHouse re-prints (`1.0` to `1`, `1e3` to `1000`) is then the same value to every
+/// condition. That is a claim about the VM this corpus is written against, not about the VM on
+/// this branch, where `Num` equality is still variant-exact and the re-print is observable. Green
+/// here therefore means "safe after that change", which is why the change has to land first.
+///
+/// Integer tokens keep their digits on both sides and a digit change there would be observable
+/// either way, so integers still compare exactly. Everything else has to match outright.
+fn values_equivalent(a: &Value, b: &Value) -> bool {
+ match (a, b) {
+ (Value::Number(a), Value::Number(b)) => {
+ if a.is_f64() || b.is_f64() {
+ a.as_f64() == b.as_f64()
+ } else {
+ a == b
+ }
+ }
+ (Value::Array(a), Value::Array(b)) => {
+ a.len() == b.len() && a.iter().zip(b).all(|(a, b)| values_equivalent(a, b))
+ }
+ (Value::Object(a), Value::Object(b)) => {
+ a.len() == b.len()
+ && a.iter()
+ .all(|(key, a)| b.get(key).is_some_and(|b| values_equivalent(a, b)))
+ }
+ _ => a == b,
+ }
+}
+
+/// The oracle itself: the numeric blur must stay confined to float representation, or every
+/// assertion in this file weakens with it.
+#[test]
+fn the_equivalence_oracle_blurs_only_float_representation() {
+ let value = |text: &str| serde_json::from_str::<Value>(text).expect("oracle cases parse");
+ let eq = |a: &str, b: &str| values_equivalent(&value(a), &value(b));
+ assert!(eq(r#"{"round":1.0}"#, r#"{"round":1}"#));
+ assert!(eq(r#"{"exp":1e3}"#, r#"{"exp":1000}"#));
+ assert!(eq(r#"{"deep":[{"x":-0.0}]}"#, r#"{"deep":[{"x":-0}]}"#));
+ assert!(
+ !eq(r#"{"n":1}"#, r#"{"n":"1"}"#),
+ "a string is not its number"
+ );
+ assert!(!eq(r#"{"n":1}"#, r#"{"n":2}"#));
+ assert!(
+ !eq(r#"{"a":1}"#, r#"{"a":1,"b":2}"#),
+ "a leaked key must fail"
+ );
+ assert!(
+ !eq(r#"{"n":9007199254740993}"#, r#"{"n":9007199254740992}"#),
+ "integer digits stay load-bearing past 2^53"
+ );
+}