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): stop seeding every person for a narrow person cohort (#102005)

Matheus Batistacde642559078
diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.py
index ae94d0eec95b..9f01edba2491 100644
--- a/products/cohorts/backend/backfill/readiness.py
+++ b/products/cohorts/backend/backfill/readiness.py
@@ -148,7 +148,9 @@ def _stamp_readiness(run: CohortBackfillRun, cohort_id: int, spec: _ReadinessSpe
try:
current_shape = FilterShapeHashes.from_filters(cohort.filters)
pinned_shape = FilterShapeHashes.from_filters(participation.pinned_filters)
- composition_stale = current_shape.composition_repair_kind(pinned_shape, cohort.filters) == run.backfill_kind
+ composition_stale = run.backfill_kind in current_shape.composition_repair_kinds(
+ pinned_shape, cohort.filters
+ )
except Exception:
# An unreadable definition cannot prove readiness and must not trap the finalizer in retries.
composition_stale = True
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index b94daacbf960..d5f0f8060715 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -149,16 +149,14 @@ class TestBackfillReadiness(BaseTest):
@parameterized.expand(KINDS)
def test_composition_edit_before_supersession_cannot_stamp(
- self, name: str, make_run, stamp, hash_column: str, stamp_column: str, *_edits
+ self, _name: str, make_run, stamp, hash_column: str, stamp_column: str, *_edits
) -> None:
- filters = self._filters(7, person_hash="person-a")
- if name == "person_properties":
- filters["properties"]["values"] = filters["properties"]["values"][1:]
- cohort = Cohort.objects.create(team=self.team, cohort_type=CohortType.REALTIME, filters=filters)
- run = make_run(self.team.id, cohort.id, "cohort_created")
- assert run is not None
+ # A mixed cohort for both kinds: negating its person leaf moves the definition and no kind
+ # hash, and a person run that pinned the old tree seeded only what could move that tree.
+ cohort, run = self._cohort_and_run(make_run)
pinned_hash = getattr(cohort, hash_column)
+ assert cohort.filters is not None
cohort.filters["properties"]["values"][-1]["negation"] = True
cohort.save(update_fields=["filters"])
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 82f9fae114b0..b554c0018a1b 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -40,6 +40,7 @@ from products.cohorts.backend.models.leaf_shape import (
FilterShapeHashes,
extract_behavioral_leaf_shape_hash,
extract_leaf_shape_hash,
+ extract_person_composition_hash,
extract_person_leaf_shape_hash,
)
from products.cohorts.backend.realtime_teams import is_realtime_cohort_team
@@ -379,12 +380,14 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
new_shape_hash = extract_leaf_shape_hash(self.filters)
new_behavioral_shape_hash = extract_behavioral_leaf_shape_hash(self.filters)
new_person_shape_hash = extract_person_leaf_shape_hash(self.filters)
+ new_person_composition_hash = extract_person_composition_hash(self.filters)
stored_shape_hash = self.__dict__.get("filters_shape_hash")
stored_behavioral_shape_hash = self.__dict__.get("behavioral_filters_shape_hash")
stored_person_shape_hash = self.__dict__.get("person_filters_shape_hash")
previous_behavioral_shape_hash = stored_behavioral_shape_hash
previous_person_shape_hash = stored_person_shape_hash
previous_shape_hash = None
+ previous_person_composition_hash = None
if not self._state.adding:
persisted_query = Cohort.objects.filter(id=self.pk, team_id=self.team_id)
@@ -407,9 +410,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
# Recomputing those baselines from filters would lose that invalidation signal.
try:
previous_shape_hash = extract_leaf_shape_hash(persisted["filters"])
+ previous_person_composition_hash = extract_person_composition_hash(persisted["filters"])
except Exception:
# A malformed baseline must not disable invalidation for a valid replacement.
previous_shape_hash = None
+ previous_person_composition_hash = None
if stored_shape_hash is None:
stored_shape_hash = persisted["filters_shape_hash"]
if stored_behavioral_shape_hash is None:
@@ -442,16 +447,20 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
person_shape_changed = not self._state.adding and previous_person_shape_hash != new_person_shape_hash
current_shape = FilterShapeHashes(
- definition=new_shape_hash, behavioral=new_behavioral_shape_hash, person=new_person_shape_hash
+ definition=new_shape_hash,
+ behavioral=new_behavioral_shape_hash,
+ person=new_person_shape_hash,
+ person_composition=new_person_composition_hash,
)
previous_shape = FilterShapeHashes(
definition=previous_shape_hash,
behavioral=previous_behavioral_shape_hash,
person=previous_person_shape_hash,
+ person_composition=previous_person_composition_hash,
)
- repair_kind = current_shape.composition_repair_kind(previous_shape, self.filters)
- behavioral_shape_changed |= repair_kind == "behavioral"
- person_shape_changed |= repair_kind == "person_property"
+ repair_kinds = current_shape.composition_repair_kinds(previous_shape, self.filters)
+ behavioral_shape_changed |= "behavioral" in repair_kinds
+ person_shape_changed |= "person_property" in repair_kinds
self.filters_shape_hash = new_shape_hash
self.behavioral_filters_shape_hash = new_behavioral_shape_hash
diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.py
index 1dc2d3c3124c..51351dc75f3f 100644
--- a/products/cohorts/backend/models/leaf_shape.py
+++ b/products/cohorts/backend/models/leaf_shape.py
@@ -9,6 +9,8 @@ from posthog.dataclasses import frozen
_I32_MIN = -(2**31)
_I32_MAX = 2**31 - 1
+RepairKind = Literal["behavioral", "person_property"]
+
class BehavioralLeafKey(NamedTuple):
"""The behavioral-leaf fields Stage 1 hashes into a `LeafStateKey`.
@@ -123,10 +125,16 @@ def _canonical(node: object) -> str:
return json.dumps(node, sort_keys=True, separators=(",", ":"))
-def _render_definition(node: object) -> list[object] | None:
+def _render_definition(node: object, *, person_view: bool = False) -> list[object] | None:
"""Render one filter node into an order-insensitive, JSON-serializable form, or `None` if it
contributes nothing to the definition.
+ `person_view` renders the tree as a person backfill run sees it. The seeder pins only person
+ leaves and holds every other leaf unknown while deciding whether a person's leaf truths can move
+ the cohort (`rust/cohort-seeder/src/domain/person_relevance.rs`), and an unknown reads the same
+ whatever the leaf says or whether it is negated, so every non-person leaf renders as one
+ anonymous marker and the group dedupe collapses any number of them into one.
+
Group children are deduped and sorted because AND and OR are commutative and idempotent, so a
reordered or repeated criterion is the same definition. A group of one operand renders as that
operand: the cohort editor shows its AND/OR toggle even on a single criterion, and a toggle with
@@ -148,7 +156,7 @@ def _render_definition(node: object) -> list[object] | None:
if node_type in ("AND", "OR"):
unique: dict[str, list[object]] = {}
for child in node.get("values") or []:
- if (rendered := _render_definition(child)) is not None:
+ if (rendered := _render_definition(child, person_view=person_view)) is not None:
unique.setdefault(_canonical(rendered), rendered)
# Rust retains empty groups and excludes their cohort from realtime evaluation.
children = [unique[key] for key in sorted(unique)]
@@ -157,6 +165,10 @@ def _render_definition(node: object) -> list[object] | None:
return [node_type, children]
negation = node.get("negation") is True
+ if node_type == "person":
+ return ["person", node.get("conditionHash"), negation]
+ if person_view:
+ return ["unknown"]
if node_type == "behavioral":
return [
"behavioral",
@@ -172,8 +184,6 @@ def _render_definition(node: object) -> list[object] | None:
),
negation,
]
- if node_type == "person":
- return ["person", node.get("conditionHash"), negation]
if node_type == "cohort":
return ["cohort", node.get("value"), negation or node.get("operator") == "not_in"]
return [node_type]
@@ -190,10 +200,25 @@ def extract_leaf_shape_hash(filters: dict | None) -> str:
Keep the leaf fields in lockstep with Rust: behavioral leaves via `BehavioralLeafKey`; person
conditionHash; cohort value; the negation rules in `_render_definition`.
"""
+ return _fingerprint(filters, person_view=False)
+
+
+def extract_person_composition_hash(filters: dict | None) -> str:
+ """Fingerprint the definition as a person backfill run sees it: person leaves by condition hash
+ and negation, every other leaf one anonymous unknown, in the AND/OR tree they sit in.
+
+ The seeder emits a person only when their leaf truths can move this tree, so the person state a
+ run stores is valid for this fingerprint alone. An edit that moves it and not the person hash
+ owes a person run, which `FilterShapeHashes.composition_repair_kinds` decides.
+ """
+ return _fingerprint(filters, person_view=True)
+
+
+def _fingerprint(filters: dict | None, *, person_view: bool) -> str:
if not filters or not (properties := filters.get("properties")):
return ""
- rendered = _render_definition(properties)
+ rendered = _render_definition(properties, person_view=person_view)
if rendered is None:
return ""
return hashlib.sha256(_canonical(rendered).encode()).hexdigest()
@@ -214,6 +239,7 @@ class FilterShapeHashes:
definition: str | None
behavioral: str | None
person: str | None
+ person_composition: str | None
@classmethod
def from_filters(cls, filters: dict | None) -> "FilterShapeHashes":
@@ -221,25 +247,39 @@ class FilterShapeHashes:
definition=extract_leaf_shape_hash(filters),
behavioral=extract_behavioral_leaf_shape_hash(filters),
person=extract_person_leaf_shape_hash(filters),
+ person_composition=extract_person_composition_hash(filters),
)
- def composition_repair_kind(
- self, previous: "FilterShapeHashes", filters: dict | None
- ) -> Literal["behavioral", "person_property"] | None:
+ def composition_repair_kinds(self, previous: "FilterShapeHashes", filters: dict | None) -> frozenset[RepairKind]:
+ """The kinds a definition change must re-run beyond the ones its leaf-hash changes already fire.
+
+ Behavioral leaf state is per leaf and survives a composition change, so a behavioral run only
+ re-reconciles the tree: one is owed when the definition moved and no leaf hash fires a run.
+ A behavioral run nulls `last_backfill_events_at`. Strict flag routing reads that stamp, so
+ it is the kind chosen here.
+
+ Person state is not per leaf. The seeder emits a person only when their leaf truths can move
+ the tree it pinned, so what a run stored is valid for that tree alone, and a person run is
+ owed whenever the tree as the person path sees it moved and the person hash did not, whatever
+ else the same save changed. It is also owed on any definition change when no behavioral run
+ re-walks the tree, because it is then the only run that reconciles the cohort.
+ """
if previous.definition is None or previous.definition == self.definition:
- return None
+ return frozenset()
leaf_types = {leaf.get("type") for leaf in walk_filter_leaves((filters or {}).get("properties"))}
person_backfillable = bool(self.person) and "person_metadata" not in leaf_types
# Match the run creators: an unhashed behavioral leaf can trigger a run, but person metadata cannot.
- if previous.behavioral != self.behavioral and "behavioral" in leaf_types:
- return None
- if previous.person != self.person and person_backfillable:
- return None
-
- # Either kind reconciles the whole tree. Prefer the events stamp used by strict flag routing.
- if self.behavioral:
- return "behavioral"
- if person_backfillable:
- return "person_property"
- return None
+ behavioral_run_fires = previous.behavioral != self.behavioral and "behavioral" in leaf_types
+ person_run_fires = previous.person != self.person and person_backfillable
+
+ behavioral_repair = bool(self.behavioral) and not behavioral_run_fires and not person_run_fires
+ behavioral_run_rewalks = behavioral_run_fires or behavioral_repair
+
+ kinds: set[RepairKind] = set()
+ if behavioral_repair:
+ kinds.add("behavioral")
+ if person_backfillable and not person_run_fires:
+ if previous.person_composition != self.person_composition or not behavioral_run_rewalks:
+ kinds.add("person_property")
+ return frozenset(kinds)
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index baacb87b6db4..29108cd1a77c 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -35,6 +35,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
extra_person_hash: str | None = None,
behavioral_hash: str | None = "stable-condition-hash",
group_type: str = "AND",
+ cohort_ref: int | None = None,
) -> dict:
values = []
if window_days is not None:
@@ -64,6 +65,8 @@ class TestBehavioralBackfillDependencies(BaseTest):
"conditionHash": leaf_hash,
}
)
+ if cohort_ref is not None:
+ values.append({"type": "cohort", "value": cohort_ref})
return {"properties": {"type": group_type, "values": values}}
def _cohort(self, window_days: int | None = 7, *, person_hash: str | None = None) -> Cohort:
@@ -309,18 +312,39 @@ class TestBehavioralBackfillDependencies(BaseTest):
self._assert_one_debounced_task_per_kind(enqueue, redis, cohort, "cohort_created")
- def test_edit_touching_both_leaf_kinds_enqueues_one_task_per_kind(self) -> None:
+ @parameterized.expand(
+ [
+ (
+ "both_leaf_shapes",
+ {"window_days": 7, "person_hash": "person-a"},
+ {"window_days": 30, "person_hash": "person-b"},
+ ),
+ (
+ "group_operator_on_mixed",
+ {"window_days": 7, "person_hash": "person-a"},
+ {"window_days": 7, "person_hash": "person-a", "group_type": "OR"},
+ ),
+ (
+ "first_behavioral_leaf_added_with_the_group_operator",
+ {"window_days": None, "person_hash": "person-a", "extra_person_hash": "person-b"},
+ {"window_days": 7, "person_hash": "person-a", "extra_person_hash": "person-b", "group_type": "OR"},
+ ),
+ ]
+ )
+ def test_edit_owing_both_kinds_enqueues_one_task_per_kind(self, _name: str, before: dict, after: dict) -> None:
# The kinds seed different stores, so one save that moves both shapes owes a task to each, on
- # keys that cannot debounce one another. The cohort is created before the trigger allowlist
- # opens, so the create dispatches nothing real behind the edit's mocks.
- cohort = self._cohort(7, person_hash="person-a")
+ # keys that cannot debounce one another. A composition edit on a mixed cohort owes both as
+ # well: a pruning person run stores state valid only for the tree it pinned, and the
+ # behavioral run is what nulls the events stamp flags route on. The cohort is created before
+ # the trigger allowlist opens, so the create dispatches nothing real behind the edit's mocks.
+ cohort = Cohort.objects.create(team=self.team, cohort_type=CohortType.REALTIME, filters=self._filters(**before))
redis = self._redis()
with (
override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
):
- cohort.filters = self._filters(30, person_hash="person-b")
+ cohort.filters = self._filters(**after)
cohort.save()
self._assert_one_debounced_task_per_kind(enqueue, redis, cohort, "cohort_edited")
@@ -338,12 +362,6 @@ class TestBehavioralBackfillDependencies(BaseTest):
@parameterized.expand(
[
- (
- "group_operator_on_mixed",
- {"window_days": 7, "person_hash": "person-a"},
- {"window_days": 7, "person_hash": "person-a", "group_type": "OR"},
- CohortBackfillKind.BEHAVIORAL,
- ),
(
"group_operator_on_person_only",
{"window_days": None, "person_hash": "person-a", "extra_person_hash": "person-b"},
@@ -355,6 +373,18 @@ class TestBehavioralBackfillDependencies(BaseTest):
},
CohortBackfillKind.PERSON_PROPERTY,
),
+ (
+ "cohort_reference_swapped_on_person_only",
+ {"window_days": None, "person_hash": "person-a", "cohort_ref": 4242},
+ {"window_days": None, "person_hash": "person-a", "cohort_ref": 9999},
+ CohortBackfillKind.PERSON_PROPERTY,
+ ),
+ (
+ "cohort_reference_swapped_on_mixed",
+ {"window_days": 7, "person_hash": "person-a", "cohort_ref": 4242},
+ {"window_days": 7, "person_hash": "person-a", "cohort_ref": 9999},
+ CohortBackfillKind.BEHAVIORAL,
+ ),
(
"last_person_leaf_removed",
{"window_days": 7, "person_hash": "person-a"},
@@ -373,8 +403,10 @@ class TestBehavioralBackfillDependencies(BaseTest):
self, _name: str, before: dict, after: dict, kind: CohortBackfillKind
) -> None:
# Reconcile evaluates the whole tree whichever kind it runs for, so one run repairs the
- # cohort. Removing the last person leaf is in this set because the person run its hash change
- # would ask for is refused: the cohort has no person leaf left to pin.
+ # cohort. A reference swap moves no person-view fingerprint, so the person run is owed only
+ # where no behavioral run re-walks the tree. Removing the last person leaf is in this set
+ # because the person run its hash change would ask for is refused: the cohort has no person
+ # leaf left to pin.
cohort = Cohort.objects.create(team=self.team, cohort_type=CohortType.REALTIME, filters=self._filters(**before))
redis = self._redis()
with (
@@ -388,7 +420,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
self._assert_one_debounced_task(enqueue, redis, cohort, kind)
@parameterized.expand([("group_operator", None), ("empty_and", "AND"), ("empty_or", "OR")])
- def test_composition_edit_nulls_the_events_stamp_and_moves_no_kind_hash(
+ def test_composition_edit_nulls_both_stamps_and_moves_no_kind_hash(
self, _name: str, empty_group: str | None
) -> None:
cohort = self._cohort(7, person_hash="person-a")
@@ -418,7 +450,7 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)
self.assertEqual(cohort.person_filters_shape_hash, old_person_hash)
self.assertIsNone(cohort.last_backfill_events_at)
- self.assertEqual(cohort.last_backfill_person_properties_at, ready_at)
+ self.assertIsNone(cohort.last_backfill_person_properties_at)
self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
self.assertEqual(self._orphan_count(), before + 1)
diff --git a/products/cohorts/backend/models/test/test_leaf_shape.py b/products/cohorts/backend/models/test/test_leaf_shape.py
index 511bbcf88794..85782df38fac 100644
--- a/products/cohorts/backend/models/test/test_leaf_shape.py
+++ b/products/cohorts/backend/models/test/test_leaf_shape.py
@@ -5,6 +5,7 @@ from parameterized import parameterized
from products.cohorts.backend.models.leaf_shape import (
extract_behavioral_leaf_shape_hash,
extract_leaf_shape_hash,
+ extract_person_composition_hash,
extract_person_leaf_shape_hash,
walk_filter_leaves,
)
@@ -32,6 +33,7 @@ def _group(group_type: str, *values: dict) -> dict:
_BEHAVIORAL = _behavioral_leaf()
_OTHER_BEHAVIORAL = _behavioral_leaf(conditionHash="ffffffffffffffff")
_PERSON = {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}
+_OTHER_PERSON = {"type": "person", "conditionHash": "bbbbbbbbbbbbbbbb"}
_COHORT_REF = {"type": "cohort", "value": 42}
@@ -118,6 +120,83 @@ class TestLeafShape(SimpleTestCase):
)
self.assertEqual(extract_person_leaf_shape_hash(before), extract_person_leaf_shape_hash(after))
+ @parameterized.expand(
+ [
+ ("root_group_operator", _group("AND", _BEHAVIORAL, _PERSON), _group("OR", _BEHAVIORAL, _PERSON), True),
+ (
+ "inner_group_operator",
+ _group("AND", _group("AND", _BEHAVIORAL, _PERSON), _OTHER_PERSON),
+ _group("AND", _group("OR", _BEHAVIORAL, _PERSON), _OTHER_PERSON),
+ True,
+ ),
+ (
+ "person_negation",
+ _group("AND", _BEHAVIORAL, _PERSON),
+ _group("AND", _BEHAVIORAL, {**_PERSON, "negation": True}),
+ True,
+ ),
+ (
+ "person_leaf_moved_between_groups",
+ _group("OR", _group("AND", _PERSON, _OTHER_PERSON), _BEHAVIORAL),
+ _group("OR", _PERSON, _group("AND", _OTHER_PERSON, _BEHAVIORAL)),
+ True,
+ ),
+ (
+ "cohort_reference_beside_person_leaves",
+ _group("OR", _PERSON, _OTHER_PERSON),
+ _group("OR", _PERSON, _OTHER_PERSON, _COHORT_REF),
+ True,
+ ),
+ (
+ "behavioral_identity",
+ _group("AND", _BEHAVIORAL, _PERSON),
+ _group("AND", _OTHER_BEHAVIORAL, _PERSON),
+ False,
+ ),
+ (
+ "behavioral_negation",
+ _group("AND", _BEHAVIORAL, _PERSON),
+ _group("AND", {**_BEHAVIORAL, "negation": True}, _PERSON),
+ False,
+ ),
+ (
+ "behavioral_hash_lost",
+ _group("AND", _BEHAVIORAL, _PERSON),
+ _group("AND", _behavioral_leaf(conditionHash=None), _PERSON),
+ False,
+ ),
+ (
+ "cohort_reference_beside_a_behavioral_leaf",
+ _group("AND", _BEHAVIORAL, _PERSON),
+ _group("AND", _BEHAVIORAL, _PERSON, _COHORT_REF),
+ False,
+ ),
+ (
+ "person_leaves_swapped_between_anonymous_partners",
+ _group("OR", _group("AND", _BEHAVIORAL, _PERSON), _group("AND", _OTHER_BEHAVIORAL, _OTHER_PERSON)),
+ _group("OR", _group("AND", _BEHAVIORAL, _OTHER_PERSON), _group("AND", _OTHER_BEHAVIORAL, _PERSON)),
+ False,
+ ),
+ ]
+ )
+ def test_person_composition_sees_the_tree_around_person_leaves_and_nothing_inside_the_others(
+ self, _name: str, before: dict, after: dict, moves: bool
+ ) -> None:
+ # A fingerprint that saw inside the leaves a person run holds unknown would fire a person scan
+ # on every behavioral edit of a mixed cohort; one that missed the tree would leave the seeds
+ # pruned under the old tree standing.
+ before_filters, after_filters = {"properties": before}, {"properties": after}
+ self.assertNotEqual(extract_leaf_shape_hash(before_filters), extract_leaf_shape_hash(after_filters))
+ fingerprints = (
+ extract_person_composition_hash(before_filters),
+ extract_person_composition_hash(after_filters),
+ )
+ self.assertNotEqual(fingerprints[0], "")
+ if moves:
+ self.assertNotEqual(*fingerprints)
+ else:
+ self.assertEqual(*fingerprints)
+
@parameterized.expand(
[
(
diff --git a/rust/cohort-core/src/hogvm/globals.rs b/rust/cohort-core/src/hogvm/globals.rs
index 930de5a93b08..868a3980c2ae 100644
--- a/rust/cohort-core/src/hogvm/globals.rs
+++ b/rust/cohort-core/src/hogvm/globals.rs
@@ -145,16 +145,27 @@ pub fn build_person_scan_globals(
person_id: Uuid,
properties: &str,
) -> Result<Value, GlobalsError> {
- // Quiet parse: a seeder scan failure must not increment the stream processor's Stage 1
- // counter — the seeder meters its own skipped rows.
- let person_properties = parse_optional_json_quiet(Some(properties), "person_properties")?;
- Ok(person_scope_globals(
- team_id.0,
- &person_id.to_string(),
- person_properties,
+ Ok(person_scan_globals(
+ team_id,
+ person_id,
+ parse_person_scan_properties(properties)?,
))
}
+/// The parse half of [`build_person_scan_globals`], for a caller that reads the parsed blob before
+/// deciding whether any condition needs the globals at all.
+///
+/// Quiet: a seeder scan failure must not increment the stream processor's Stage 1 counter — the
+/// seeder meters its own skipped rows.
+pub fn parse_person_scan_properties(properties: &str) -> Result<Value, GlobalsError> {
+ parse_optional_json_quiet(Some(properties), "person_properties")
+}
+
+/// The build half of [`build_person_scan_globals`], taking the already-parsed blob.
+pub fn person_scan_globals(team_id: TeamId, person_id: Uuid, properties: Value) -> Value {
+ person_scope_globals(team_id.0, &person_id.to_string(), properties)
+}
+
/// The one constructor of the `{"person":{"id","properties"},"project":{"id"}}` shape.
fn person_scope_globals(team_id: i32, person_id: &str, person_properties: Value) -> Value {
json!({
@@ -470,10 +481,16 @@ mod tests {
e.person_properties = Some(properties.to_string());
let from_event = build_person_property_globals(&e).unwrap();
let from_scan = build_person_scan_globals(TeamId(42), person_id, properties).unwrap();
- assert_eq!(
- serde_json::to_string(&from_scan).unwrap(),
- serde_json::to_string(&from_event).unwrap(),
+ // The halves are held to the same oracle as the whole, because the seeder reads the
+ // parsed blob before deciding whether it needs globals and so calls them separately.
+ let from_halves = person_scan_globals(
+ TeamId(42),
+ person_id,
+ parse_person_scan_properties(properties).unwrap(),
);
+ let expected = serde_json::to_string(&from_event).unwrap();
+ assert_eq!(serde_json::to_string(&from_scan).unwrap(), expected);
+ assert_eq!(serde_json::to_string(&from_halves).unwrap(), expected);
}
assert_eq!(
build_person_scan_globals(TeamId(42), person_id, "").unwrap()["person"]["properties"],
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
index e39518fce205..5b59838eaea6 100644
--- a/rust/cohort-core/src/hogvm/mod.rs
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -21,6 +21,6 @@ pub use executor::{
};
pub use globals::{
build_behavioral_globals, build_person_property_globals, build_person_scan_globals,
- GlobalsError,
+ parse_person_scan_properties, person_scan_globals, GlobalsError,
};
pub use program::ConditionProgram;
diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rs
index 43e2239f5a41..479ec59e5809 100644
--- a/rust/cohort-seeder/src/app/execute.rs
+++ b/rust/cohort-seeder/src/app/execute.rs
@@ -27,6 +27,7 @@ use crate::store::runs::RunKind;
use crate::store::RenderedError;
use super::deliver::{self, ProduceError};
+use super::person_execute::PersonChunkStats;
use super::prepare::PreparedBehavioral;
use super::settings::ProducerSettings;
@@ -110,6 +111,7 @@ pub(super) async fn execute_chunk(
Ok(_) => ChunkOutcome::Confirmed {
lease,
tiles_produced,
+ detail: ConfirmedDetail::Behavioral,
},
Err(halt) => resolve_halt(&store, halt, &shutdown, retry_backoff).await,
}
@@ -245,11 +247,20 @@ fn render_reason<E: std::error::Error>(reason: &HaltReason<E>) -> RenderedError
}
}
+/// What a confirmed chunk's log line says beyond its tile count. The behavioral path's counters
+/// already read per day and band, so only the person path carries a payload.
+#[derive(Debug)]
+pub(super) enum ConfirmedDetail {
+ Behavioral,
+ Person(PersonChunkStats),
+}
+
#[derive(Debug)]
pub(super) enum ChunkOutcome {
Confirmed {
lease: ChunkLease,
tiles_produced: u64,
+ detail: ConfirmedDetail,
},
Failed {
lease: ChunkLease,
@@ -274,9 +285,21 @@ pub(super) fn record_task_result(
Ok(ChunkOutcome::Confirmed {
lease,
tiles_produced,
+ detail,
}) => {
counter!(CHUNKS_CONFIRMED, "kind" => kind.as_str()).increment(1);
- info!(?lease, tiles_produced, "chunk confirmed");
+ match detail {
+ ConfirmedDetail::Behavioral => info!(?lease, tiles_produced, "chunk confirmed"),
+ ConfirmedDetail::Person(stats) => info!(
+ ?lease,
+ tiles_produced,
+ persons_scanned = stats.persons_scanned,
+ nonmatchers = stats.nonmatchers,
+ pruned = stats.pruned,
+ shortcut_evaluations = stats.shortcut_evaluations,
+ "chunk confirmed",
+ ),
+ }
}
Ok(ChunkOutcome::Failed {
lease,
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index 9248a9a1d301..47fe5e576646 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -408,7 +408,7 @@ impl SeederOrchestrator {
producer: self.producer.clone(),
pacer: person.pacer.clone(),
producer_settings: self.settings.producer,
- emit_nonmatchers: person_settings.emit_nonmatchers,
+ emission: person_settings.emission,
retry_backoff: self.settings.retry_backoff,
};
let shutdown = shutdown.clone();
diff --git a/rust/cohort-seeder/src/app/person_execute.rs b/rust/cohort-seeder/src/app/person_execute.rs
index 5efdb7d0847d..603f7227d7bd 100644
--- a/rust/cohort-seeder/src/app/person_execute.rs
+++ b/rust/cohort-seeder/src/app/person_execute.rs
@@ -19,20 +19,22 @@ use crate::clickhouse::person_scanner::{PersonRow, PersonScanError, PersonScanne
use crate::clickhouse::person_sql::PersonScanSpec;
use crate::clickhouse::scan_volume::{self, ScanKind};
use crate::domain::{
- CancelCause, ClaimedChunk, Halted, PersonChunkSpecError, PersonEvaluator, PersonRowOutcome,
- PersonSeedContext, PinnedPersonRun, RecordStats, RetryBackoffPolicy, StreamedChunk,
+ CancelCause, ClaimedChunk, Halted, PersonChunkSpecError, PersonEmissionPolicy, PersonEvaluator,
+ PersonRowOutcome, PersonSeedContext, PinnedPersonRun, RecordStats, RetryBackoffPolicy,
+ StreamedChunk,
};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
use crate::observability::metrics::{
- MetricTimer, PERSONS_SCANNED, PERSON_CHUNK_SCAN_DURATION_SECONDS, PERSON_HOGVM_ERRORS,
- PERSON_NONMATCHERS_SKIPPED, PERSON_ROWS_SKIPPED, PERSON_SEEDS_PRODUCED,
+ MetricTimer, PERSONS_SCANNED, PERSON_CHUNK_SCAN_DURATION_SECONDS, PERSON_CONDITIONS_SHORTCUT,
+ PERSON_HOGVM_ERRORS, PERSON_NONMATCHERS_SKIPPED, PERSON_ROWS_PRUNED, PERSON_ROWS_SKIPPED,
+ PERSON_SCAN_FILTER, PERSON_SEEDS_PRODUCED, PRUNE_REASON_IRRELEVANT,
};
use crate::store::chunks::PgChunkStore;
use crate::store::lease::LeaseHandle;
use super::deliver::{self, InFlight, ProduceError, ProduceStop};
-use super::execute::{mark_produced_halt, resolve_halt, ChunkOutcome};
+use super::execute::{mark_produced_halt, resolve_halt, ChunkOutcome, ConfirmedDetail};
use super::settings::ProducerSettings;
/// The owned inputs to one person chunk's processing task.
@@ -45,10 +47,20 @@ pub(super) struct PersonChunkTaskContext {
pub(super) producer: SeedTileProducer,
pub(super) pacer: TilePacer,
pub(super) producer_settings: ProducerSettings,
- pub(super) emit_nonmatchers: bool,
+ pub(super) emission: PersonEmissionPolicy,
pub(super) retry_backoff: RetryBackoffPolicy,
}
+/// What one person chunk's fold came to, rendered on the `chunk confirmed` line so a run's shape is
+/// legible without joining four counters.
+#[derive(Debug, Default, Clone, Copy)]
+pub(super) struct PersonChunkStats {
+ pub(super) persons_scanned: u64,
+ pub(super) nonmatchers: u64,
+ pub(super) pruned: u64,
+ pub(super) shortcut_evaluations: u64,
+}
+
pub(super) async fn execute_person_chunk(
ctx: PersonChunkTaskContext,
shutdown: CancellationToken,
@@ -62,26 +74,26 @@ pub(super) async fn execute_person_chunk(
producer,
pacer,
producer_settings,
- emit_nonmatchers,
+ emission,
retry_backoff,
} = ctx;
let lease_cancel = lease.cancellation_token();
// PreMark: stream the range scan, evaluating and enqueueing one seed per emitted person.
- let (streamed, inflight) = match stream_chunk(
+ let (streamed, inflight, stats) = match stream_chunk(
chunk,
&run,
&scanner,
&producer,
&pacer,
producer_settings,
- emit_nonmatchers,
+ emission,
&lease_cancel,
&shutdown,
)
.await
{
- Ok(pair) => pair,
+ Ok(triple) => triple,
Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
// PreMark: CAS `scanning`→`produced` — the row is still `scanning` on failure.
@@ -102,6 +114,7 @@ pub(super) async fn execute_person_chunk(
Ok(_) => ChunkOutcome::Confirmed {
lease,
tiles_produced: seeds_produced,
+ detail: ConfirmedDetail::Person(stats),
},
Err(halt) => resolve_halt(&store, halt, &shutdown, retry_backoff).await,
}
@@ -110,32 +123,38 @@ pub(super) async fn execute_person_chunk(
#[allow(clippy::too_many_arguments)]
async fn stream_chunk(
chunk: ClaimedChunk,
- run: &PinnedPersonRun,
+ run: &Arc<PinnedPersonRun>,
scanner: &PersonScanner,
producer: &SeedTileProducer,
pacer: &TilePacer,
settings: ProducerSettings,
- emit_nonmatchers: bool,
+ emission: PersonEmissionPolicy,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
-) -> Result<(StreamedChunk, InFlight), Halted<ClaimedChunk, PersonChunkError>> {
+) -> Result<(StreamedChunk, InFlight, PersonChunkStats), Halted<ClaimedChunk, PersonChunkError>> {
let spec = match run.chunk_spec(&chunk.spec()) {
Ok(spec) => spec,
Err(error) => return Err(Halted::failed(chunk, PersonChunkError::Spec(error))),
};
- let scan_spec = PersonScanSpec::new(spec.team_id, run.scan_since, spec.range);
+ let scan_spec = PersonScanSpec::new(
+ spec.team_id,
+ run.scan_since,
+ spec.range,
+ run.scan_key_filter(emission),
+ );
+ counter!(PERSON_SCAN_FILTER, "outcome" => scan_spec.filter_outcome().as_str()).increment(1);
let mut cursor = match scanner.scan_rows(&scan_spec, chunk.spec()) {
Ok(cursor) => cursor,
Err(error) => return Err(Halted::failed(chunk, PersonChunkError::Scan(error))),
};
- let mut evaluator =
- PersonEvaluator::new(spec.team_id, run.conditions.clone(), emit_nonmatchers);
+ let mut evaluator = PersonEvaluator::new(run, emission);
let seed_ctx = PersonSeedContext {
scanned_at: spec.scanned_at,
run_id: spec.lease.run_id(),
claim_epoch: spec.lease.epoch(),
};
let mut inflight = InFlight::new(settings.max_inflight.get());
+ let mut stats = PersonChunkStats::default();
let mut seeds_produced: u64 = 0;
// Started after setup so the spec/cursor early returns don't seed the histogram with
// near-zero samples.
@@ -151,6 +170,7 @@ async fn stream_chunk(
&mut inflight,
pacer,
settings,
+ &mut stats,
&mut seeds_produced,
lease_cancel,
shutdown,
@@ -158,7 +178,7 @@ async fn stream_chunk(
.await;
let volume = scan_volume::observe(ScanKind::Person, &cursor);
match folded {
- Ok(()) => Ok((chunk.into_streamed(seeds_produced, volume), inflight)),
+ Ok(()) => Ok((chunk.into_streamed(seeds_produced, volume), inflight, stats)),
Err(stop) => Err(stop.into_halt(chunk)),
}
}
@@ -174,6 +194,7 @@ async fn fold_person_rows(
inflight: &mut InFlight,
pacer: &TilePacer,
settings: ProducerSettings,
+ stats: &mut PersonChunkStats,
seeds_produced: &mut u64,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
@@ -198,8 +219,10 @@ async fn fold_person_rows(
return Ok(());
};
counter!(PERSONS_SCANNED).increment(1);
- let (outcome, stats) = evaluator.evaluate_row(&row.id, &row.properties, seed_ctx);
- record_row_stats(stats);
+ stats.persons_scanned += 1;
+ let (outcome, row_stats) = evaluator.evaluate_row(&row.id, &row.properties, seed_ctx);
+ stats.shortcut_evaluations += u64::from(row_stats.shortcut_evaluations);
+ record_row_stats(row_stats);
match outcome {
PersonRowOutcome::Seed(seed) => {
if let Err(stop) = deliver::enqueue_one(
@@ -218,8 +241,13 @@ async fn fold_person_rows(
counter!(PERSON_SEEDS_PRODUCED).increment(1);
}
PersonRowOutcome::NonMatcher => {
+ stats.nonmatchers += 1;
counter!(PERSON_NONMATCHERS_SKIPPED).increment(1);
}
+ PersonRowOutcome::Irrelevant => {
+ stats.pruned += 1;
+ counter!(PERSON_ROWS_PRUNED, "reason" => PRUNE_REASON_IRRELEVANT).increment(1);
+ }
PersonRowOutcome::Skipped(skip) => {
counter!(PERSON_ROWS_SKIPPED, "reason" => skip.as_str()).increment(1);
}
@@ -253,6 +281,9 @@ impl From<ProduceStop> for PersonStreamStop {
}
fn record_row_stats(stats: RecordStats) {
+ if stats.shortcut_evaluations > 0 {
+ counter!(PERSON_CONDITIONS_SHORTCUT).increment(u64::from(stats.shortcut_evaluations));
+ }
if stats.unknown_functions > 0 {
counter!(PERSON_HOGVM_ERRORS, "class" => VmErrorClass::UnknownFunction.as_str())
.increment(u64::from(stats.unknown_functions));
diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rs
index 06c4129f766c..1ea4de4d1aa2 100644
--- a/rust/cohort-seeder/src/app/prepare.rs
+++ b/rust/cohort-seeder/src/app/prepare.rs
@@ -18,8 +18,8 @@ use sqlx::PgPool;
use tracing::{debug, info, warn};
use crate::domain::{
- plan_days, ConditionAnalyses, ConditionClass, Lookback, PersonRunValidation, PinnedPersonRun,
- PinnedRun, PinnedWarning, PlanCaps, RunId,
+ plan_days, ConditionAnalyses, ConditionClass, Lookback, PersonEmissionPolicy,
+ PersonRunValidation, PinnedPersonRun, PinnedRun, PinnedWarning, PlanCaps, ProjectedKeys, RunId,
};
use crate::observability::metrics::{
team_label, BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_CLASSIFIED,
@@ -307,6 +307,7 @@ async fn prepare_person(
};
if reported_runs.insert(run_id) {
record_pinned_warnings(&validated.warnings);
+ report_person_analysis(run_id, &validated.run);
}
if validated
.warnings
@@ -352,6 +353,42 @@ async fn prepare_person(
}
}
+/// One line per run naming what its conditions need from a row and whether ClickHouse can drop
+/// key-less persons for it.
+///
+/// `prunable_keys` is what the relevant-only policy would filter on; whether it actually did is the
+/// per-chunk `seeder_person_scan_filter_total{outcome}` reading. Together they separate "the run
+/// cannot be filtered" from "this deployment is healing".
+fn report_person_analysis(run_id: RunId, run: &PinnedPersonRun) {
+ let census = run.analysis_census();
+ let prunable_keys = run.scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort);
+ if run.composable_cohorts() == Some(0) {
+ // Every participation is structurally excluded, so the consumer composes none of them and
+ // no seed this run emits registers membership for a cohort of its own. It will scan the
+ // team and confirm every chunk, which reads exactly like a successful backfill.
+ warn!(
+ ?run_id,
+ "person run composes no cohort; no participation of its own registers membership",
+ );
+ }
+ info!(
+ ?run_id,
+ conditions = run.conditions.len(),
+ key_decidable = census.key_decidable,
+ always_evaluate = %census.render_always_evaluate(),
+ composable_cohorts = ?run.composable_cohorts(),
+ prunable_key_count = ?prunable_keys.as_ref().map(ProjectedKeys::count),
+ "person run analyzed",
+ );
+ // The key names are customer-defined and uncapped, so they follow the same rule as the
+ // behavioral census's read sets below.
+ debug!(
+ ?run_id,
+ prunable_keys = ?prunable_keys.as_ref().map(|keys| keys.iter().collect::<Vec<_>>()),
+ "person run prunable keys",
+ );
+}
+
/// The eligible run ids of one kind — the per-kind label on every shared chunk metric resolves
/// through here, so the mapping lives in one place.
pub(super) fn run_ids_of_kind(
diff --git a/rust/cohort-seeder/src/app/prime.rs b/rust/cohort-seeder/src/app/prime.rs
index 5238ca6b1ae0..4cb1853ef950 100644
--- a/rust/cohort-seeder/src/app/prime.rs
+++ b/rust/cohort-seeder/src/app/prime.rs
@@ -10,6 +10,10 @@
//! them out should show every value it can ever show. That does put a flat zero line on those
//! panels for values production never produces.
//!
+//! The person path's prune and scan-filter counters are here for the same reason: the canary reads
+//! "the filter applied and pruning did the work", and a run that pruned nothing has to be legible as
+//! zero rather than as a missing series.
+//!
//! The two `seeder_shadow_compare_*` counters solve the same problem without priming, which is why
//! they are absent here. Their `team_id` label has no value until a chunk is scanned.
//! `seeder_shadow_compare_total` then publishes one of a closed `result` vocabulary per chunk, so
@@ -19,8 +23,12 @@
use cohort_core::hogvm::VmErrorClass;
use metrics::counter;
+use crate::clickhouse::person_sql::ScanFilterOutcome;
use crate::clickhouse::ScanSkipReason;
-use crate::observability::metrics::{CHUNKS_POISONED, EVENTS_SKIPPED, HOGVM_ERRORS};
+use crate::observability::metrics::{
+ CHUNKS_POISONED, EVENTS_SKIPPED, HOGVM_ERRORS, PERSON_CONDITIONS_SHORTCUT, PERSON_ROWS_PRUNED,
+ PERSON_SCAN_FILTER, PRUNE_REASON_IRRELEVANT,
+};
use crate::store::runs::RunKind;
/// Register every label value of the gated counters at zero. Call once, after the recorder is
@@ -35,6 +43,13 @@ pub fn prime_zero_series() {
for kind in RunKind::ALL {
counter!(CHUNKS_POISONED, "kind" => kind.as_str()).increment(0);
}
+ // The person canary is read against these two: a run that pruned nothing and a run whose filter
+ // never rendered have to look different from an exporter that dropped the family.
+ counter!(PERSON_ROWS_PRUNED, "reason" => PRUNE_REASON_IRRELEVANT).increment(0);
+ counter!(PERSON_CONDITIONS_SHORTCUT).increment(0);
+ for outcome in ScanFilterOutcome::ALL {
+ counter!(PERSON_SCAN_FILTER, "outcome" => outcome.as_str()).increment(0);
+ }
}
#[cfg(test)]
@@ -51,12 +66,18 @@ mod tests {
metrics::with_local_recorder(&recorder, prime_zero_series);
let rendered = handle.render();
- // The three readings a validation run is gated on: malformed blobs skipped, HogVM aborts
- // on an unresolvable reference, and chunks dead-lettered at the attempt cap.
+ // The readings a validation run is gated on: malformed blobs skipped, HogVM aborts on an
+ // unresolvable reference, chunks dead-lettered at the attempt cap, persons pruned as
+ // irrelevant, and whether the person key filter applied or was refused as too long.
for series in [
format!("{EVENTS_SKIPPED}{{reason=\"globals_parse_error\"}} 0"),
format!("{HOGVM_ERRORS}{{class=\"unknown_ref\"}} 0"),
format!("{CHUNKS_POISONED}{{kind=\"behavioral\"}} 0"),
+ format!("{PERSON_ROWS_PRUNED}{{reason=\"irrelevant\"}} 0"),
+ format!("{PERSON_SCAN_FILTER}{{outcome=\"key_presence\"}} 0"),
+ format!("{PERSON_SCAN_FILTER}{{outcome=\"none\"}} 0"),
+ format!("{PERSON_SCAN_FILTER}{{outcome=\"too_long\"}} 0"),
+ format!("{PERSON_CONDITIONS_SHORTCUT} 0"),
] {
assert!(
rendered.contains(&series),
diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rs
index a573f4fbda1c..f34933603f23 100644
--- a/rust/cohort-seeder/src/app/settings.rs
+++ b/rust/cohort-seeder/src/app/settings.rs
@@ -6,7 +6,7 @@ use std::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize};
use std::time::Duration;
use crate::config::Config;
-use crate::domain::{BackoffPolicyError, PlanCaps, RetryBackoffPolicy};
+use crate::domain::{BackoffPolicyError, PersonEmissionPolicy, PlanCaps, RetryBackoffPolicy};
use crate::store::runs::RunKind;
use crate::store::{LeaseDuration, LeaseDurationError, MaxAttempts, MaxAttemptsError};
@@ -22,7 +22,8 @@ pub struct PersonSettings {
/// The person path's own slot budget: a person chunk never occupies a behavioral slot, so a
/// long person scan cannot stall live behavioral seeding.
pub max_concurrent_chunks: NonZeroUsize,
- pub emit_nonmatchers: bool,
+ /// Which scanned persons a chunk emits. `SEEDER_PERSON_EMIT_NONMATCHERS` names the choice.
+ pub emission: PersonEmissionPolicy,
/// Whether completion discovery may surface person runs. Separate from the seed gate so the
/// reconcile half can be staged after the processor fleet decodes `reconcile_person` tiles —
/// seeding a person run is inert, dispatching its tiles to an old processor is not.
@@ -160,7 +161,9 @@ impl TryFrom<&Config> for OrchestratorSettings {
config.seeder_person_max_concurrent_chunks,
)
.ok_or(OrchestratorSettingsError::ZeroPersonConcurrency)?,
- emit_nonmatchers: config.seeder_person_emit_nonmatchers,
+ emission: PersonEmissionPolicy::from_emit_nonmatchers(
+ config.seeder_person_emit_nonmatchers,
+ ),
reconcile_dispatch: config.seeder_person_reconcile_dispatch_enabled,
};
person.validate_scan_budget(config.seeder_ch_max_execution_time_secs)?;
diff --git a/rust/cohort-seeder/src/clickhouse/person_sql.rs b/rust/cohort-seeder/src/clickhouse/person_sql.rs
index 43b0049b9224..a79dbbad60f5 100644
--- a/rust/cohort-seeder/src/clickhouse/person_sql.rs
+++ b/rust/cohort-seeder/src/clickhouse/person_sql.rs
@@ -16,10 +16,50 @@
//! the streaming aggregation bounded; the client's external-group-by spill guard backstops a silent
//! optimizer fallback. Only the boundary query orders its output — the range scan's fold is
//! order-independent, and an unneeded `ORDER BY` would materialize the whole chunk result.
+//!
+//! The range scan may also carry a key-presence filter, which drops a person whose latest blob is a
+//! JSON object holding none of the keys the run's conditions read — a person the fold would prune
+//! anyway, at the cost of transferring and decoding their whole property bag first. See
+//! [`key_presence_predicate`] for why it admits every non-object blob.
use cohort_core::filters::TeamId;
-use crate::domain::{PersonRange, UtcMillis};
+use crate::clickhouse::sql::key_list;
+use crate::domain::{PersonRange, ProjectedKeys, UtcMillis};
+
+/// The rendered ceiling one scan may reach, leaving about 2 KB of margin.
+///
+/// The `cohort_seeder` ClickHouse profile runs `readonly=2`, under which a query over 8192 bytes is
+/// POSTed as `readonly=1` and fails with code 164. The profile lives in the infrastructure
+/// repository, not here, so this constant cannot be derived — re-check it against the profile
+/// rather than against this comment. Conservative in the safe direction: the `?` → `??` escaping in
+/// [`clickhouse_string_literal`](super::sql::clickhouse_string_literal) is undone by the client's
+/// template parser, so the query that reaches the server is never longer than the text measured
+/// here.
+const MAX_RENDERED_SCAN_BYTES: usize = 6144;
+
+/// What became of a run's key filter on one chunk, as a bounded metric label.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ScanFilterOutcome {
+ /// The scan drops object rows carrying none of the run's keys.
+ KeyPresence,
+ /// The run asked for no filter: the healer policy, or a condition the VM has to decide.
+ None,
+ /// The rendered filter would have pushed the query past the readonly ceiling.
+ TooLong,
+}
+
+impl ScanFilterOutcome {
+ pub const ALL: [Self; 3] = [Self::KeyPresence, Self::None, Self::TooLong];
+
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::KeyPresence => "key_presence",
+ Self::None => "none",
+ Self::TooLong => "too_long",
+ }
+ }
+}
/// The rendered person scan's inputs, constructed only from already-proven types.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -27,16 +67,47 @@ pub struct PersonScanSpec {
team_id: TeamId,
scan_since_ms: i64,
range: PersonRange,
+ key_filter: Option<ProjectedKeys>,
+ filter_outcome: ScanFilterOutcome,
}
impl PersonScanSpec {
- pub fn new(team_id: TeamId, scan_since: UtcMillis, range: PersonRange) -> Self {
- Self {
+ /// `key_filter` names the top-level `properties` keys a person must carry to be worth scanning;
+ /// `None` scans the whole range.
+ ///
+ /// The size guard lives here rather than in the renderer, which renders once to measure and
+ /// drops the filter if it does not fit. [`person_scan_sql`] then stays a pure rendering of a
+ /// spec already proven to fit, at the cost of one extra render per chunk.
+ pub fn new(
+ team_id: TeamId,
+ scan_since: UtcMillis,
+ range: PersonRange,
+ key_filter: Option<ProjectedKeys>,
+ ) -> Self {
+ let filter_outcome = match &key_filter {
+ Some(_) => ScanFilterOutcome::KeyPresence,
+ None => ScanFilterOutcome::None,
+ };
+ let spec = Self {
team_id,
scan_since_ms: scan_since.as_i64(),
range,
+ key_filter,
+ filter_outcome,
+ };
+ if person_scan_sql(&spec).len() <= MAX_RENDERED_SCAN_BYTES {
+ return spec;
+ }
+ Self {
+ key_filter: None,
+ filter_outcome: ScanFilterOutcome::TooLong,
+ ..spec
}
}
+
+ pub const fn filter_outcome(&self) -> ScanFilterOutcome {
+ self.filter_outcome
+ }
}
pub fn person_boundaries_sql(team_id: TeamId, scan_since: UtcMillis) -> String {
@@ -49,13 +120,41 @@ pub fn person_boundaries_sql(team_id: TeamId, scan_since: UtcMillis) -> String {
pub fn person_scan_sql(spec: &PersonScanSpec) -> String {
format!(
- "SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = {team} AND {outer_range} AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = {team} AND {prefilter_range}\n AND recent._timestamp >= fromUnixTimestamp64Milli({since})\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli({since})\nSETTINGS optimize_aggregation_in_order = 1",
+ "SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = {team} AND {outer_range} AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = {team} AND {prefilter_range}\n AND recent._timestamp >= fromUnixTimestamp64Milli({since})\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli({since}){key_filter}\nSETTINGS optimize_aggregation_in_order = 1",
team = spec.team_id.0,
outer_range = range_predicate("p", spec.range),
// The prefilter carries the same range, against its own table reference, so the primary key
// prunes it too.
prefilter_range = range_predicate("recent", spec.range),
since = spec.scan_since_ms,
+ key_filter = spec
+ .key_filter
+ .as_ref()
+ .map(key_presence_predicate)
+ .unwrap_or_default(),
+ )
+}
+
+/// Drop object blobs carrying none of `keys`.
+///
+/// Costs two server-side JSON parses per scanned group, `JSONType` and `JSONExtractKeys`, against
+/// the scan's `max_execution_time` budget. Cheap next to the transfer and per-row evaluation it
+/// removes, but it is new ClickHouse work and belongs in the rollout measurement.
+///
+/// Every *non*-object blob is admitted, deliberately. `JSONType` reports `Null` for a missing,
+/// empty, literal-`null` or malformed blob — and also for a well-formed document holding a number
+/// ClickHouse cannot represent, which `serde_json` parses and whose keys the VM then reads. Dropping
+/// the `Null` class would therefore drop genuine members, so the filter admits a strict superset of
+/// what the seeder can emit and exactness stays with the VM.
+///
+/// The aggregate is spelled out twice rather than referencing the `properties` output alias: a bare
+/// column name in `HAVING` binds to that alias, which is the mistake
+/// `no_column_reference_can_resolve_to_the_output_alias` exists to catch. ClickHouse computes one
+/// `argMax` state for the repeated expression.
+fn key_presence_predicate(keys: &ProjectedKeys) -> String {
+ let key_list = key_list(keys);
+ format!(
+ "\n AND (JSONType(argMax(p.properties, p.version)) != 'Object' OR hasAny(JSONExtractKeys(argMax(p.properties, p.version)), [{key_list}]))"
)
}
@@ -86,6 +185,15 @@ mod tests {
PersonRange::new(lo, hi).unwrap()
}
+ fn scan_spec(range: PersonRange, key_filter: Option<ProjectedKeys>) -> PersonScanSpec {
+ PersonScanSpec::new(TeamId(2), SINCE, range, key_filter)
+ }
+
+ fn keys(names: &[&str]) -> ProjectedKeys {
+ ProjectedKeys::new(names.iter().map(|name| (*name).to_owned()).collect())
+ .expect("the test key sets are non-empty")
+ }
+
#[test]
fn boundaries_sql_is_byte_frozen() {
assert_eq!(
@@ -101,35 +209,86 @@ mod tests {
// Band 0: nil lo (tautology) with a bounded hi.
assert_eq!(
- person_scan_sql(&PersonScanSpec::new(
- TeamId(2),
- SINCE,
- range(Uuid::nil(), Some(boundary_a)),
- )),
+ person_scan_sql(&scan_spec(range(Uuid::nil(), Some(boundary_a)), None)),
"SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = 2 AND p.id >= toUUID('00000000-0000-0000-0000-000000000000') AND p.id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = 2 AND recent.id >= toUUID('00000000-0000-0000-0000-000000000000') AND recent.id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee')\n AND recent._timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
);
// Interior band: both bounds present.
assert_eq!(
- person_scan_sql(&PersonScanSpec::new(
- TeamId(2),
- SINCE,
- range(boundary_a, Some(boundary_b)),
- )),
+ person_scan_sql(&scan_spec(range(boundary_a, Some(boundary_b)), None)),
"SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = 2 AND p.id >= toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND p.id < toUUID('7f000000-0000-0000-0000-000000000001') AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = 2 AND recent.id >= toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND recent.id < toUUID('7f000000-0000-0000-0000-000000000001')\n AND recent._timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
);
// Last band: unbounded high.
assert_eq!(
- person_scan_sql(&PersonScanSpec::new(
- TeamId(2),
- SINCE,
- range(boundary_b, None)
- )),
+ person_scan_sql(&scan_spec(range(boundary_b, None), None)),
"SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = 2 AND p.id >= toUUID('7f000000-0000-0000-0000-000000000001') AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = 2 AND recent.id >= toUUID('7f000000-0000-0000-0000-000000000001')\n AND recent._timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
);
}
+ /// The filter is appended to the `HAVING` clause, before `SETTINGS`, and spells the aggregate
+ /// out twice rather than naming the `properties` output alias. Frozen byte for byte because the
+ /// predicate's exact text is what `tests/ch_person_key_filter.rs` measures against a real server.
+ #[test]
+ fn scan_sql_is_byte_frozen_with_the_key_presence_filter() {
+ let boundary = Uuid::parse_str("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee").unwrap();
+ assert_eq!(
+ person_scan_sql(&scan_spec(
+ range(Uuid::nil(), Some(boundary)),
+ Some(keys(&["email", "plan"])),
+ )),
+ "SELECT toString(p.id) AS id, argMax(p.properties, p.version) AS properties\nFROM person AS p\nWHERE p.team_id = 2 AND p.id >= toUUID('00000000-0000-0000-0000-000000000000') AND p.id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = 2 AND recent.id >= toUUID('00000000-0000-0000-0000-000000000000') AND recent.id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee')\n AND recent._timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli(1780000000000)\n AND (JSONType(argMax(p.properties, p.version)) != 'Object' OR hasAny(JSONExtractKeys(argMax(p.properties, p.version)), ['email', 'plan']))\nSETTINGS optimize_aggregation_in_order = 1"
+ );
+ }
+
+ /// A key is customer text. The single quote is the one escape whose failure would be an
+ /// injection rather than a wrong answer, and a bare `?` is swallowed by the client's own
+ /// template parser before the SQL is sent.
+ #[test]
+ fn key_literals_are_escaped_for_both_the_server_and_the_client_template() {
+ let rendered = person_scan_sql(&scan_spec(
+ range(Uuid::nil(), None),
+ Some(keys(&["quote' OR 1 = 1 --", "back\\slash", "why?fields"])),
+ ));
+ let predicate = rendered
+ .split_once("OR hasAny(")
+ .expect("the filter renders")
+ .1;
+ assert!(
+ predicate.starts_with(
+ "JSONExtractKeys(argMax(p.properties, p.version)), ['back\\\\slash', 'quote\\' OR 1 = 1 --', 'why??fields'])"
+ ),
+ "key literals escaped as: {predicate}"
+ );
+ }
+
+ /// The `cohort_seeder` profile runs `readonly=2`, which refuses a query over 8192 bytes: a key
+ /// list long enough to cross that must cost the filter, not every chunk of the run.
+ #[test]
+ fn an_oversized_key_list_drops_the_filter_rather_than_the_query() {
+ let short = scan_spec(range(Uuid::nil(), None), Some(keys(&["email"])));
+ assert_eq!(short.filter_outcome(), ScanFilterOutcome::KeyPresence);
+ assert!(person_scan_sql(&short).contains("hasAny("));
+
+ let long: Vec<String> = (0..500)
+ .map(|index| format!("property_number_{index}"))
+ .collect();
+ let long = ProjectedKeys::new(long.into_iter().collect()).unwrap();
+ let spec = scan_spec(range(Uuid::nil(), None), Some(long));
+ assert_eq!(spec.filter_outcome(), ScanFilterOutcome::TooLong);
+ let rendered = person_scan_sql(&spec);
+ assert!(
+ !rendered.contains("hasAny("),
+ "the filter survived the guard"
+ );
+ assert!(rendered.len() <= MAX_RENDERED_SCAN_BYTES);
+
+ assert_eq!(
+ scan_spec(range(Uuid::nil(), None), None).filter_outcome(),
+ ScanFilterOutcome::None
+ );
+ }
+
/// The byte-frozen tests above compare each query against a copy of itself, so they accept any
/// SQL the renderer emits, including SQL no ClickHouse can execute. This one states the property
/// that made the shipped query unexecutable: an unqualified column reference binds to the
@@ -142,11 +301,9 @@ mod tests {
let mut rendered = vec![person_boundaries_sql(TeamId(2), SINCE)];
// Both predicate shapes: a bounded range and the final unbounded one.
for hi in [Some(boundary), None] {
- rendered.push(person_scan_sql(&PersonScanSpec::new(
- TeamId(2),
- SINCE,
- range(Uuid::nil(), hi),
- )));
+ for filter in [None, Some(keys(&["email", "plan"]))] {
+ rendered.push(person_scan_sql(&scan_spec(range(Uuid::nil(), hi), filter)));
+ }
}
for sql in &rendered {
diff --git a/rust/cohort-seeder/src/clickhouse/sql.rs b/rust/cohort-seeder/src/clickhouse/sql.rs
index 8470f0cfc499..0556a8bcf205 100644
--- a/rust/cohort-seeder/src/clickhouse/sql.rs
+++ b/rust/cohort-seeder/src/clickhouse/sql.rs
@@ -160,17 +160,21 @@ fn render_blob(column: &str, alias: &str, source: &BlobSource) -> String {
/// 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(", ");
+ let key_list = key_list(keys);
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 {
+/// `keys` as a comma-separated list of string literals, for an `IN (...)` or an array literal.
+pub(crate) fn key_list(keys: &ProjectedKeys) -> String {
+ keys.iter()
+ .map(clickhouse_string_literal)
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+pub(crate) fn clickhouse_string_literal(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('\'');
for character in value.chars() {
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index e4dca1e4907c..962de7c955ff 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -252,8 +252,16 @@ pub struct Config {
#[envconfig(default = "1")]
pub seeder_person_max_concurrent_chunks: usize,
- /// Emit empty-`matched` seeds for scanned non-matchers. They heal stale-TRUE state and cost
- /// only a point-read on absent records (the consumer's no-create rule).
+ /// Which scanned persons a person chunk emits.
+ ///
+ /// On, this is the healer cadence: every scanned person is seeded, including empty-`matched`
+ /// ones, which is what retracts stale TRUE state. It has to see everyone, so it prunes nothing
+ /// and asks ClickHouse for no key filter.
+ ///
+ /// Off, a chunk emits only a person whose leaf truths can move a participating cohort's verdict
+ /// against an absent prior. Conditions whose keys the person's blob lacks are decided from a
+ /// verdict cached at validation instead of through the VM, and when every condition is decidable
+ /// that way the scan drops key-less rows in ClickHouse rather than transferring them.
#[envconfig(default = "true")]
pub seeder_person_emit_nonmatchers: bool,
diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rs
index 81324b4a6a8b..c18b26536f30 100644
--- a/rust/cohort-seeder/src/domain/aggregate.rs
+++ b/rust/cohort-seeder/src/domain/aggregate.rs
@@ -31,6 +31,9 @@ pub struct RecordStats {
pub non_matched: u32,
pub unknown_functions: u32,
pub vm_failures: VmFailureCounts,
+ /// Conditions the person path decided from the run's cached vacuous verdict rather than by
+ /// running the VM. Always zero on the behavioral path.
+ pub shortcut_evaluations: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 3d7f0c770c18..879f7b858a34 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -2,7 +2,8 @@
//!
//! No module here reaches into PostgreSQL, ClickHouse, or Kafka. The internal
//! dependency order is strictly downward:
-//! `ids` ← {`condition`, `window`} ← `chunk` ← {`plan`, `pinned`, `aggregate`} ← `person`,
+//! `ids` ← {`condition`, `window`} ← `chunk` ← {`plan`, `pinned`, `aggregate`} ←
+//! {`person_relevance`, `person_analysis`} ← `person`,
//! except that `chunk` reaches back into `person` for the `PersonRange` vocabulary its spec
//! carries. The seed wire contract (`SeedTile`/`PersonSeed` and the ids that ride them) lives in
//! `cohort_core::seed` — shared with the processor — and is re-exported here.
@@ -18,6 +19,8 @@ pub mod ids;
pub mod ledger;
pub mod partition;
pub mod person;
+pub mod person_analysis;
+pub mod person_relevance;
pub mod pinned;
pub mod plan;
pub mod projection;
@@ -57,10 +60,12 @@ pub use ledger::{MarkerFold, MarkerLedger, SettledVerdict};
pub use partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};
pub use person::{
person_chunk_sentinel_day, tile_ranges, EvaluatedConditions, PersonChunkSpec,
- PersonChunkSpecError, PersonEvaluator, PersonPinnedSnapshot, PersonPlanError, PersonRange,
- PersonRangeError, PersonRowOutcome, PersonRowSkip, PersonRunValidation, PersonSeedContext,
- PinnedPersonRun, ValidatedPinnedPersonRun, MAX_PERSON_CHUNKS,
+ PersonChunkSpecError, PersonEmissionPolicy, PersonEvaluator, PersonPinnedSnapshot,
+ PersonPlanError, PersonRange, PersonRangeError, PersonRowOutcome, PersonRowSkip,
+ PersonRunValidation, PersonSeedContext, PinnedPersonRun, ValidatedPinnedPersonRun,
+ MAX_PERSON_CHUNKS,
};
+pub use person_analysis::{AlwaysEvaluateReason, PersonAnalysisCensus};
pub use pinned::{
PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,
PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
index cd6ea7f0a7f7..47d11980f0bc 100644
--- a/rust/cohort-seeder/src/domain/person.rs
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -9,11 +9,12 @@
//! decode would strand claimed chunks `scanning`.
use std::collections::{BTreeMap, HashSet};
+use std::sync::Arc;
use chrono::NaiveDate;
use cohort_core::filters::{CohortId, TeamFilters, TeamId};
use cohort_core::hogvm::{
- build_person_scan_globals, classify_vm_error, CohortEvaluator, ConditionProgram, EvalOutcome,
+ parse_person_scan_properties, person_scan_globals, CohortEvaluator, ConditionProgram,
};
use cohort_core::seed::PersonSeed;
use cohort_core::{LeafStateKey, StateVariant};
@@ -24,10 +25,13 @@ use uuid::Uuid;
use super::aggregate::RecordStats;
use super::chunk::{ChunkLease, ChunkSpec};
use super::ids::{ClaimEpoch, ConditionHash, RunId, ScannedAtMs, UtcMillis};
+use super::person_analysis::{ConditionVerdict, PersonAnalysisCensus, PersonConditionAnalyses};
+use super::person_relevance::{ConditionIndex, Relevance, RelevanceOracle, TruthVector};
use super::pinned::{
resolve_timezone, ParticipationSet, PinnedDropReason, PinnedError, PinnedParticipation,
PinnedParticipationState, PinnedWarning,
};
+use super::projection::ProjectedKeys;
/// The wire cap a single seed's `evaluated` list admits; validation enforces it run-wide.
pub use cohort_core::seed::MAX_PERSON_SEED_HASHES;
@@ -141,6 +145,11 @@ pub struct PersonPinnedSnapshot {
}
/// A person run proven scannable: `scan_since` present, at least one condition surviving.
+///
+/// The two analyses are built once here, from the participation set validation assembles and then
+/// drops: [`PersonConditionAnalyses`] says what each condition needs from a row, and
+/// [`RelevanceOracle`] says which leaf truths can move a participating cohort. Both are pure
+/// functions of the pinned payload, so a run re-validated on another replica derives the same ones.
#[derive(Debug)]
pub struct PinnedPersonRun {
pub run_id: RunId,
@@ -148,6 +157,36 @@ pub struct PinnedPersonRun {
pub scan_since: UtcMillis,
pub conditions: EvaluatedConditions,
pub horizon_days: u32,
+ analyses: PersonConditionAnalyses,
+ relevance: RelevanceOracle,
+}
+
+/// Which scanned persons a chunk emits.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PersonEmissionPolicy {
+ /// The healer cadence. It exists to retract stale state, so it has to see every scanned person:
+ /// nothing is pruned and no scan filter is applied.
+ EveryScannedPerson,
+ /// Every other run: emit only a person whose leaf truths can move a participating cohort's
+ /// verdict against an absent prior.
+ RelevantToSomeCohort,
+}
+
+impl PersonEmissionPolicy {
+ pub const fn from_emit_nonmatchers(emit_nonmatchers: bool) -> Self {
+ if emit_nonmatchers {
+ Self::EveryScannedPerson
+ } else {
+ Self::RelevantToSomeCohort
+ }
+ }
+
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::EveryScannedPerson => "every_scanned_person",
+ Self::RelevantToSomeCohort => "relevant_to_some_cohort",
+ }
+ }
}
#[derive(Debug)]
@@ -233,6 +272,8 @@ impl PinnedPersonRun {
return Ok(PersonRunValidation::Retired { warnings });
}
let conditions = EvaluatedConditions::new(surviving)?;
+ let analyses = PersonConditionAnalyses::build(snapshot.team_id, &conditions);
+ let relevance = RelevanceOracle::build(participation.filters(), &conditions);
Ok(PersonRunValidation::Seedable(ValidatedPinnedPersonRun {
run: PinnedPersonRun {
@@ -241,12 +282,53 @@ impl PinnedPersonRun {
scan_since,
conditions,
horizon_days: payload.person_horizon_days,
+ analyses,
+ relevance,
},
warnings,
uncovered_cohorts,
}))
}
+ /// The top-level `properties` keys ClickHouse may drop a chunk's rows on, or `None` to scan the
+ /// whole range.
+ ///
+ /// Three things have to hold together. The policy has to be the relevant-only one, because the
+ /// healer must see every scanned person. Every condition has to be key-decidable, or a dropped
+ /// row might have decided one the VM had to run. And the vacuous vector — the truths every
+ /// dropped row carries — has to be irrelevant, because that is the verdict being discarded.
+ pub fn scan_key_filter(&self, emission: PersonEmissionPolicy) -> Option<ProjectedKeys> {
+ match emission {
+ PersonEmissionPolicy::EveryScannedPerson => return None,
+ PersonEmissionPolicy::RelevantToSomeCohort => {}
+ }
+ match self.relevance.judge(&self.analyses.vacuous_truths()?) {
+ Relevance::CanChangeSomeCohort => None,
+ Relevance::IrrelevantToEveryCohort => {
+ self.analyses.keys_if_every_condition_is_key_decidable()
+ }
+ }
+ }
+
+ /// The verdict `index` reaches on `object` without the VM, or `None` when it needs one.
+ fn shortcut(
+ &self,
+ index: ConditionIndex,
+ object: Option<&serde_json::Map<String, Value>>,
+ ) -> Option<ConditionVerdict> {
+ self.analyses.shortcut(index, object)
+ }
+
+ /// How the run's conditions classified, for the per-run log line.
+ pub fn analysis_census(&self) -> PersonAnalysisCensus {
+ self.analyses.census()
+ }
+
+ /// How many participations the relevance oracle walks, or `None` when it proves nothing.
+ pub fn composable_cohorts(&self) -> Option<usize> {
+ self.relevance.composable_cohorts()
+ }
+
/// Narrow a claimed chunk to the person path, after proving it belongs to this run/team. This
/// is the one deliberate `SChunkMs` → [`ScannedAtMs`] bridge: the claim stamp becomes the
/// seed's LWW instant, and re-claims re-stamp so LWW converges to the fresher snapshot.
@@ -323,6 +405,21 @@ impl EvaluatedConditions {
pub fn iter(&self) -> impl Iterator<Item = &(ConditionHash, ConditionProgram)> {
self.0.iter()
}
+
+ /// Each condition with its [`ConditionIndex`]. The conversion is total because
+ /// [`EvaluatedConditions::new`] refuses a set larger than the wire cap the index restates.
+ pub fn indexed(
+ &self,
+ ) -> impl Iterator<Item = (ConditionIndex, &ConditionHash, &ConditionProgram)> {
+ self.0
+ .iter()
+ .enumerate()
+ .map(|(position, (hash, program))| {
+ let index = ConditionIndex::new(position)
+ .expect("EvaluatedConditions::new caps the set at MAX_PERSON_SEED_HASHES");
+ (index, hash, program)
+ })
+ }
}
/// The mint constants a chunk's seeds share.
@@ -337,8 +434,12 @@ pub struct PersonSeedContext {
#[derive(Debug, PartialEq, Eq)]
pub enum PersonRowOutcome {
Seed(PersonSeed),
- /// Evaluated fully, nothing matched, and non-matcher emission is off.
+ /// Evaluated fully, nothing matched, and the policy is relevant-only.
NonMatcher,
+ /// Evaluated fully, and the truths reached cannot move any participating cohort's verdict
+ /// against an absent prior — so the seed would produce a record write and a recompose that
+ /// changes nothing.
+ Irrelevant,
Skipped(PersonRowSkip),
}
@@ -361,22 +462,25 @@ impl PersonRowSkip {
}
}
-/// The pure per-row fold: build scan globals, run every surviving condition through the shared
-/// evaluator, and mint at most one [`PersonSeed`]. Unit-testable without ClickHouse or Kafka.
+/// The pure per-row fold: decide each surviving condition — from the run's cached vacuous verdict
+/// where the blob's keys allow, from the VM otherwise — and mint at most one [`PersonSeed`].
+/// Unit-testable without ClickHouse or Kafka.
pub struct PersonEvaluator {
- team_id: TeamId,
- conditions: EvaluatedConditions,
+ run: Arc<PinnedPersonRun>,
evaluator: CohortEvaluator,
- emit_nonmatchers: bool,
+ emission: PersonEmissionPolicy,
+ /// One slot per condition, refilled per row: `Some` where the blob's key set already decides the
+ /// condition. A field rather than a local so the fold allocates nothing per person.
+ shortcuts: Vec<Option<ConditionVerdict>>,
}
impl PersonEvaluator {
- pub fn new(team_id: TeamId, conditions: EvaluatedConditions, emit_nonmatchers: bool) -> Self {
+ pub fn new(run: &Arc<PinnedPersonRun>, emission: PersonEmissionPolicy) -> Self {
Self {
- team_id,
- conditions,
+ run: Arc::clone(run),
evaluator: CohortEvaluator::new(),
- emit_nonmatchers,
+ emission,
+ shortcuts: Vec::with_capacity(run.conditions.len()),
}
}
@@ -393,33 +497,61 @@ impl PersonEvaluator {
stats,
);
};
- let Ok(globals) = build_person_scan_globals(self.team_id, person_id, properties) else {
+ let Ok(properties) = parse_person_scan_properties(properties) else {
return (
PersonRowOutcome::Skipped(PersonRowSkip::InvalidProperties),
stats,
);
};
- self.evaluator.set_globals(globals);
- let mut evaluated = Vec::with_capacity(self.conditions.len());
+ let Self {
+ run,
+ evaluator,
+ emission,
+ shortcuts,
+ } = self;
+
+ // A non-object blob is not "an object missing keys": an array makes `GET_GLOBAL` coerce a
+ // string key to a number and error, so those rows keep going through the VM.
+ let object = properties.as_object();
+ shortcuts.clear();
+ shortcuts.extend(
+ run.conditions
+ .indexed()
+ .map(|(index, _, _)| run.shortcut(index, object)),
+ );
+ if shortcuts.iter().any(Option::is_none) {
+ evaluator.set_globals(person_scan_globals(run.team_id, person_id, properties));
+ }
+
+ let mut evaluated = Vec::with_capacity(run.conditions.len());
let mut matched = Vec::new();
- for (hash, program) in self.conditions.iter() {
- match self.evaluator.evaluate_detailed(program) {
- EvalOutcome::Matched(true) => {
+ let mut truths = TruthVector::ABSENT;
+ for ((index, hash, program), shortcut) in run.conditions.indexed().zip(&*shortcuts) {
+ let verdict = match shortcut {
+ Some(cached) => {
+ stats.shortcut_evaluations += 1;
+ *cached
+ }
+ None => evaluator.evaluate_detailed(program).into(),
+ };
+ match verdict {
+ ConditionVerdict::Matched(true) => {
evaluated.push(*hash);
matched.push(*hash);
+ truths.set(index);
stats.matched += 1;
}
- EvalOutcome::Matched(false) => {
+ ConditionVerdict::Matched(false) => {
evaluated.push(*hash);
stats.non_matched += 1;
}
// A hash the VM never answered is excluded from `evaluated`: its absence from
// `matched` would otherwise assert FALSE and mint a wrong `Left`.
- EvalOutcome::UnknownFunction(_) => stats.unknown_functions += 1,
- EvalOutcome::VmError(error) => stats
+ ConditionVerdict::UnknownFunction => stats.unknown_functions += 1,
+ ConditionVerdict::VmFailure(class) => stats
.vm_failures
- .increment(classify_vm_error(&error))
+ .increment(class)
.expect("per-row VM failure counts are bounded by the condition cap"),
}
}
@@ -429,11 +561,32 @@ impl PersonEvaluator {
stats,
);
}
- if matched.is_empty() && !self.emit_nonmatchers {
- return (PersonRowOutcome::NonMatcher, stats);
+ match emission {
+ PersonEmissionPolicy::EveryScannedPerson => {}
+ PersonEmissionPolicy::RelevantToSomeCohort => {
+ // A deliberate policy choice, not an optimization of the line below: it keeps
+ // `seeder_person_nonmatchers_skipped_total` counting what it has always counted.
+ // It is also *narrower* than the oracle — a collapsed oracle judges every vector
+ // relevant, the absent one included — so the two branches cannot be merged.
+ if matched.is_empty() {
+ return (PersonRowOutcome::NonMatcher, stats);
+ }
+ // Pruning models the consumer's recompose as a walk over `truths`, and that holds
+ // only while the seed asserts every pinned leaf. A condition the VM never answered
+ // is absent from `evaluated`, so the consumer keeps whatever bit it already stored
+ // for that leaf (`apply_person_seed`'s `untouched`) and composes
+ // `matched ∪ untouched`, which is not `truths`. Emit rather than judge a vector the
+ // fold will not use.
+ let asserts_every_leaf = evaluated.len() == run.conditions.len();
+ if asserts_every_leaf
+ && run.relevance.judge(&truths) == Relevance::IrrelevantToEveryCohort
+ {
+ return (PersonRowOutcome::Irrelevant, stats);
+ }
+ }
}
let seed = PersonSeed::new(
- self.team_id,
+ run.team_id,
person_id,
evaluated,
matched,
@@ -449,6 +602,7 @@ impl PersonEvaluator {
#[cfg(test)]
mod tests {
use cohort_core::filters::LeafStateMeta;
+ use cohort_core::hogvm::EvalOutcome;
use proptest::prelude::*;
use serde_json::json;
@@ -496,6 +650,89 @@ mod tests {
json!({ "properties": { "type": "AND", "values": values } })
}
+ /// `email is_set OR email not_icontains '@posthog.com'`, with the bytecode the cohort compiler
+ /// emits. The OR is what makes the vacuous vector matter: a person with no email is a member.
+ fn vacuously_true_or_filter() -> Value {
+ json!({ "properties": { "type": "OR", "values": [
+ {
+ "type": "person", "key": "email", "value": "is_set", "operator": "is_set",
+ "conditionHash": HASH_A,
+ "bytecode": ["_H", 1, 31, 32, "email", 32, "properties", 32, "person", 1, 3, 12],
+ },
+ {
+ "type": "person", "key": "email", "value": "@posthog.com",
+ "operator": "not_icontains", "conditionHash": HASH_B,
+ "bytecode": [
+ "_H", 1, 32, "%@posthog.com%", 32, "email", 32, "properties", 32, "person", 1,
+ 3, 2, "toString", 1, 20
+ ],
+ },
+ ] } })
+ }
+
+ /// `AND(person A, person B, cohort ref 99)`. The reference makes the cohort
+ /// `Excluded(HasCohortRef)` in the seeder, which freezes with cascade off — while the consumer
+ /// runs with it on and composes the cohort. The oracle has to treat it as composable.
+ fn and_with_a_cohort_reference() -> Value {
+ json!({ "properties": { "type": "AND", "values": [
+ {
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": HASH_A, "bytecode": person_bytecode("email", "[email protected]"),
+ },
+ {
+ "type": "person", "key": "plan", "value": "paid", "operator": "exact",
+ "conditionHash": HASH_B, "bytecode": person_bytecode("plan", "paid"),
+ },
+ { "type": "cohort", "value": 99 },
+ ] } })
+ }
+
+ /// A single negated person leaf at the root: `TopLevelNegation`, which both services decide the
+ /// same way and neither composes.
+ fn negated_root_filter(hash: &str) -> Value {
+ let mut leaf = json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": hash, "bytecode": person_bytecode("email", "[email protected]"),
+ });
+ leaf["negation"] = json!(true);
+ json!({ "properties": { "type": "AND", "values": [leaf] } })
+ }
+
+ /// A condition the analyzer can narrow to `person.properties.email` but the VM cannot answer,
+ /// because no native is registered under that name.
+ fn unknown_native_filter() -> Value {
+ json!({ "properties": { "type": "AND", "values": [
+ {
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": HASH_A,
+ "bytecode": [
+ "_H", 1, 32, "email", 32, "properties", 32, "person", 1, 3, 2,
+ "noSuchNativeExists", 1
+ ],
+ },
+ {
+ "type": "person", "key": "plan", "value": "paid", "operator": "exact",
+ "conditionHash": HASH_B, "bytecode": person_bytecode("plan", "paid"),
+ },
+ ] } })
+ }
+
+ /// A leaf reading `person.id`, which differs on every row and so can never be shortcut.
+ fn person_id_filter() -> Value {
+ json!({ "properties": { "type": "AND", "values": [
+ {
+ "type": "person", "key": "id", "value": "x", "operator": "exact",
+ "conditionHash": HASH_A,
+ "bytecode": ["_H", 1, 32, "x", 32, "id", 32, "person", 1, 2, 11],
+ },
+ {
+ "type": "person", "key": "plan", "value": "paid", "operator": "exact",
+ "conditionHash": HASH_B,
+ "bytecode": person_bytecode("plan", "paid"),
+ },
+ ] } })
+ }
+
fn participation(cohort_id: i32, filters: Value, superseded: bool) -> PinnedParticipation {
PinnedParticipation {
cohort_id: CohortId(cohort_id),
@@ -758,7 +995,10 @@ mod tests {
}
fn build_evaluator(emit_nonmatchers: bool) -> PersonEvaluator {
- PersonEvaluator::new(TeamId(2), seedable_run().run.conditions, emit_nonmatchers)
+ PersonEvaluator::new(
+ &Arc::new(seedable_run().run),
+ PersonEmissionPolicy::from_emit_nonmatchers(emit_nonmatchers),
+ )
}
const CLAIM_STAMP_MS: i64 = 1_783_470_000_000;
@@ -874,7 +1114,23 @@ mod tests {
let person = Uuid::from_u128(7);
let ctx = context();
- for properties in [r#"{"email":"[email protected]","plan":"paid"}"#, r#"{"email":"x"}"#] {
+ let run = Arc::new(seedable_run().run);
+ // Blobs the shortcut decides (no `email`, no `plan`) beside blobs it hands to the VM, so the
+ // oracle sees both paths. A non-object blob has to take the VM path: an array makes
+ // `GET_GLOBAL` error where an empty object yields null.
+ for properties in [
+ r#"{"email":"[email protected]","plan":"paid"}"#,
+ r#"{"email":"x"}"#,
+ r#"{"email":null}"#,
+ r#"{}"#,
+ "",
+ r#"{"other":1}"#,
+ r#"{"Email":"[email protected]","PLAN":"paid"}"#,
+ r#"null"#,
+ r#"[1]"#,
+ r#""a string""#,
+ r#"42"#,
+ ] {
let event = CohortStreamEvent {
team_id: 2,
person_id: person.to_string(),
@@ -891,18 +1147,388 @@ mod tests {
redirect_hops: 0,
};
let globals = build_person_property_globals(&event).unwrap();
- let mut evaluator = build_evaluator(true);
- let (outcome, _) = evaluator.evaluate_row(&person.to_string(), properties, &ctx);
- let PersonRowOutcome::Seed(seed) = outcome else {
- panic!("expected a seed, got {outcome:?}");
+ // `Some(true)` matched, `Some(false)` did not, `None` the VM never answered.
+ let live: Vec<Option<bool>> = run
+ .conditions
+ .iter()
+ .map(|(_, program)| {
+ match cohort_core::hogvm::evaluate_detailed(program.tokens(), globals.clone()) {
+ EvalOutcome::Matched(matched) => Some(matched),
+ EvalOutcome::UnknownFunction(_) | EvalOutcome::VmError(_) => None,
+ }
+ })
+ .collect();
+
+ let mut evaluator =
+ PersonEvaluator::new(&run, PersonEmissionPolicy::EveryScannedPerson);
+ let (outcome, stats) = evaluator.evaluate_row(&person.to_string(), properties, &ctx);
+ // The accounting has to agree too: a shortcut that reached the right verdict while
+ // miscounting a VM failure as a non-match would leave the metrics lying.
+ assert_eq!(
+ (
+ stats.matched,
+ stats.non_matched,
+ stats.unknown_functions,
+ stats
+ .vm_failures
+ .iter()
+ .map(|(_, count)| count)
+ .sum::<u32>(),
+ ),
+ (
+ live.iter()
+ .filter(|verdict| **verdict == Some(true))
+ .count() as u32,
+ live.iter()
+ .filter(|verdict| **verdict == Some(false))
+ .count() as u32,
+ 0,
+ live.iter().filter(|verdict| verdict.is_none()).count() as u32,
+ ),
+ "{properties:?} accounted differently from live evaluation"
+ );
+ let seeded: Vec<Option<bool>> = match outcome {
+ PersonRowOutcome::Seed(seed) => run
+ .conditions
+ .iter()
+ .map(|(hash, _)| {
+ seed.evaluated()
+ .contains(hash)
+ .then(|| seed.matched().contains(hash))
+ })
+ .collect(),
+ PersonRowOutcome::Skipped(PersonRowSkip::NothingEvaluated) => {
+ vec![None; run.conditions.len()]
+ }
+ other => panic!("{properties:?} produced {other:?}"),
};
- for (hash, program) in build_evaluator(true).conditions.iter() {
- let live = matches!(
- cohort_core::hogvm::evaluate_detailed(program.tokens(), globals.clone()),
- EvalOutcome::Matched(true)
- );
- assert_eq!(seed.matched().contains(hash), live, "hash {hash} diverged");
- }
+ assert_eq!(seeded, live, "{properties:?} diverged from live evaluation");
+ }
+ }
+
+ /// The emission policy is the only thing deciding whether a scanned person reaches the topic.
+ /// The run's cohort is `email = [email protected] AND plan = paid`, so a person matching one leaf writes a
+ /// record and recomposes to the same FALSE an absent record already reads.
+ #[test]
+ fn the_relevant_only_policy_prunes_a_matcher_that_cannot_move_its_cohort() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ let run = Arc::new(seedable_run().run);
+ let half = r#"{"email":"[email protected]","plan":"free"}"#;
+ let member = r#"{"email":"[email protected]","plan":"paid"}"#;
+ let neither = r#"{"email":"x"}"#;
+
+ let mut healer = PersonEvaluator::new(&run, PersonEmissionPolicy::EveryScannedPerson);
+ for properties in [half, member, neither] {
+ let (outcome, _) = healer.evaluate_row(&person, properties, &ctx);
+ assert!(
+ matches!(outcome, PersonRowOutcome::Seed(_)),
+ "the healer must see {properties}, got {outcome:?}"
+ );
+ }
+
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+ assert_eq!(
+ quiet.evaluate_row(&person, half, &ctx).0,
+ PersonRowOutcome::Irrelevant
+ );
+ // An all-false row stays a non-matcher, so that counter keeps its meaning.
+ assert_eq!(
+ quiet.evaluate_row(&person, neither, &ctx).0,
+ PersonRowOutcome::NonMatcher
+ );
+ assert!(matches!(
+ quiet.evaluate_row(&person, member, &ctx).0,
+ PersonRowOutcome::Seed(_)
+ ));
+ }
+
+ /// A vacuously true leaf under an OR makes every key-less person a member, so nothing about that
+ /// run may be pruned or filtered away. This is the case the whole design has to not break.
+ #[test]
+ fn a_vacuously_true_leaf_under_an_or_is_neither_pruned_nor_filtered() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ let run = Arc::new(
+ seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, vacuously_true_or_filter(), false)],
+ )))
+ .run,
+ );
+
+ assert_eq!(
+ run.scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort),
+ None,
+ "dropping key-less rows would drop this cohort's members"
+ );
+
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+ let (outcome, stats) = quiet.evaluate_row(&person, r#"{"other":1}"#, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("a person with no email is a member here, got {outcome:?}");
+ };
+ assert_eq!(
+ seed.matched(),
+ &[hash(HASH_B)],
+ "not_icontains is vacuously true"
+ );
+ assert_eq!(
+ stats.shortcut_evaluations, 2,
+ "both conditions are still decided without the VM"
+ );
+
+ // Every person satisfies one leaf or the other — a PostHog address through `is_set`, a
+ // missing one through `not_icontains` — which is what makes this cohort the whole team and
+ // why no row of it can be dropped.
+ let (outcome, _) = quiet.evaluate_row(&person, r#"{"email":"[email protected]"}"#, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("a PostHog address still satisfies is_set, got {outcome:?}");
+ };
+ assert_eq!(seed.matched(), &[hash(HASH_A)]);
+ }
+
+ /// Two of the filter's preconditions: the relevant-only policy, and every condition decidable
+ /// from the blob's keys. The third — an irrelevant vacuous vector — is
+ /// `a_vacuously_true_leaf_under_an_or_is_neither_pruned_nor_filtered`, and the verdict-shaped
+ /// fourth is `a_condition_the_vm_cannot_answer_on_an_empty_bag_withholds_the_scan_filter`.
+ #[test]
+ fn the_scan_key_filter_needs_the_relevant_only_policy_and_key_decidable_conditions() {
+ let decidable = seedable_run().run;
+ assert_eq!(
+ decidable
+ .scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort)
+ .as_ref()
+ .map(|keys| keys.iter().collect::<Vec<_>>()),
+ Some(vec!["email", "plan"]),
+ );
+ assert_eq!(
+ decidable.scan_key_filter(PersonEmissionPolicy::EveryScannedPerson),
+ None,
+ "the healer has to see every scanned person",
+ );
+
+ // A condition reading `person.id` cannot be decided from the blob's keys, so a dropped row
+ // might have been one it matched.
+ let reads_person_id = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, person_id_filter(), false)],
+ )))
+ .run;
+ assert_eq!(
+ reads_person_id.scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort),
+ None
+ );
+ }
+
+ /// The consumer keeps its stored bit for any leaf a seed does not assert, so a row where some
+ /// condition never answered composes `matched ∪ untouched`, not the vector the oracle judged.
+ /// Pruning such a row would lose a real flip: a person with a stored TRUE for the failing leaf
+ /// and a fresh TRUE for the other one enters the AND, and the oracle cannot see it.
+ #[test]
+ fn a_row_whose_seed_does_not_assert_every_leaf_is_never_pruned() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ // `9999` is no opcode, so the leaf loads and then fails at run time.
+ let mut leaves = person_filter_leaves(&[(HASH_A, "email", "[email protected]")]);
+ leaves["properties"]["values"]
+ .as_array_mut()
+ .unwrap()
+ .push(json!({
+ "type": "person", "key": "plan", "value": "paid", "operator": "exact",
+ "conditionHash": HASH_B, "bytecode": ["_H", 1, 9999],
+ }));
+ let run = Arc::new(
+ seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, leaves, false)],
+ )))
+ .run,
+ );
+
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+ let (outcome, stats) = quiet.evaluate_row(&person, r#"{"email":"[email protected]"}"#, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!(
+ "the failing leaf's stored bit is unknown here, so the row must seed: {outcome:?}"
+ );
+ };
+ assert_eq!(seed.evaluated(), &[hash(HASH_A)]);
+ assert_eq!(
+ stats
+ .vm_failures
+ .iter()
+ .map(|(_, count)| count)
+ .sum::<u32>(),
+ 1
+ );
+ }
+
+ /// The same hole, one level up: if a key-less row would leave a condition unanswered, ClickHouse
+ /// must not be the one to drop it, because the seeder would have asserted nothing for that leaf
+ /// and the consumer would have kept its stored bit.
+ #[test]
+ fn a_condition_the_vm_cannot_answer_on_an_empty_bag_withholds_the_scan_filter() {
+ let run = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, unknown_native_filter(), false)],
+ )))
+ .run;
+
+ // Both conditions are key-decidable — the analyzer narrows the unknown native's read set
+ // fine — so only the verdict itself withholds the filter.
+ assert_eq!(
+ run.analysis_census().key_decidable,
+ 2,
+ "the precondition under test is the verdict, not the read set"
+ );
+ assert_eq!(
+ run.scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort),
+ None
+ );
+ }
+
+ /// The contract between the two mechanisms, checked rather than reasoned: when a run renders a
+ /// key filter, every object blob ClickHouse would drop must be one the fold declines to seed.
+ /// A filter that outran the fold would silently lose members, and nothing else in the suite
+ /// compares the two.
+ #[test]
+ fn every_blob_the_key_filter_drops_is_one_the_fold_would_not_have_seeded() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ let run = Arc::new(seedable_run().run);
+ let keys = run
+ .scan_key_filter(PersonEmissionPolicy::RelevantToSomeCohort)
+ .expect("this run renders a filter");
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+
+ for dropped in [
+ r#"{}"#,
+ r#"{"other":1}"#,
+ r#"{"Email":"[email protected]","Plan":"paid"}"#,
+ r#"{"nested":{"email":"[email protected]","plan":"paid"}}"#,
+ r#"{"emails":["[email protected]"],"plans":"paid"}"#,
+ ] {
+ let map = serde_json::from_str::<Value>(dropped).unwrap();
+ let map = map.as_object().unwrap().clone();
+ assert!(
+ keys.iter().all(|key| !map.contains_key(key)),
+ "{dropped} must be one ClickHouse drops, or this case proves nothing"
+ );
+ let (outcome, _) = quiet.evaluate_row(&person, dropped, &ctx);
+ assert!(
+ !matches!(outcome, PersonRowOutcome::Seed(_)),
+ "{dropped} would be dropped by the scan yet seeded by the fold: {outcome:?}"
+ );
+ }
+ }
+
+ /// The cascade-off asymmetry, driven through `RelevanceOracle::build` rather than a hand-built
+ /// tree: the seeder calls a ref-bearing cohort `Excluded(HasCohortRef)` because it freezes with
+ /// cascade off, while the consumer composes it. Counting it as never-composed would prune its
+ /// real members. A root-negated cohort is excluded the same way in both services and is skipped.
+ #[test]
+ fn build_counts_a_ref_bearing_cohort_and_skips_a_root_negated_one() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ const HASH_C: &str = "cccccccccccccccc";
+ let run = Arc::new(
+ seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B), (2, HASH_C)]),
+ vec![
+ participation(1, and_with_a_cohort_reference(), false),
+ participation(2, negated_root_filter(HASH_C), false),
+ ],
+ )))
+ .run,
+ );
+ assert_eq!(
+ run.composable_cohorts(),
+ Some(1),
+ "the ref-bearing cohort composes; the root-negated one does not"
+ );
+
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+ // Both pinned leaves true turns the AND's unknown reference into the deciding leaf, so the
+ // verdict moves off its absent FALSE and the seed has to reach the consumer.
+ assert!(matches!(
+ quiet
+ .evaluate_row(&person, r#"{"email":"[email protected]","plan":"paid"}"#, &ctx)
+ .0,
+ PersonRowOutcome::Seed(_)
+ ));
+ // One leaf true still leaves the AND determinately false, whatever the reference resolves
+ // to, so nothing can move.
+ assert_eq!(
+ quiet
+ .evaluate_row(&person, r#"{"email":"[email protected]","plan":"free"}"#, &ctx)
+ .0,
+ PersonRowOutcome::Irrelevant
+ );
+ }
+
+ /// The negation bit has to survive `compile`: `email = [email protected] AND NOT plan = paid` composes,
+ /// and its member folds TRUE only through `bit ^ negated`. Were the bit dropped, that member
+ /// would fold to the absent FALSE and be pruned, with no error and no metric.
+ #[test]
+ fn build_keeps_the_negation_of_a_pinned_leaf_below_the_root() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ let mut leaves =
+ person_filter_leaves(&[(HASH_A, "email", "[email protected]"), (HASH_B, "plan", "paid")]);
+ leaves["properties"]["values"][1]["negation"] = json!(true);
+ let run = Arc::new(
+ seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, leaves, false)],
+ )))
+ .run,
+ );
+ assert_eq!(
+ run.composable_cohorts(),
+ Some(1),
+ "one negated leaf under a two-leaf AND is not a root negation"
+ );
+
+ let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
+ // The member: the positive leaf true, the negated one false.
+ assert!(matches!(
+ quiet
+ .evaluate_row(&person, r#"{"email":"[email protected]","plan":"free"}"#, &ctx)
+ .0,
+ PersonRowOutcome::Seed(_)
+ ));
+ // Both leaves true is a non-member, which the absent prior already reads as.
+ assert_eq!(
+ quiet
+ .evaluate_row(&person, r#"{"email":"[email protected]","plan":"paid"}"#, &ctx)
+ .0,
+ PersonRowOutcome::Irrelevant
+ );
+ }
+
+ /// Only the conditions whose keys the blob lacks skip the VM, and a non-object blob skips none.
+ #[test]
+ fn the_shortcut_count_tracks_which_keys_the_blob_carries() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+ let run = Arc::new(seedable_run().run);
+ let mut evaluator = PersonEvaluator::new(&run, PersonEmissionPolicy::EveryScannedPerson);
+
+ for (properties, expected) in [
+ (r#"{"other":1}"#, 2),
+ (r#"{}"#, 2),
+ (r#"{"email":"[email protected]"}"#, 1),
+ (r#"{"email":"[email protected]","plan":"paid"}"#, 0),
+ (r#"[1]"#, 0),
+ (r#"null"#, 0),
+ ] {
+ let (_, stats) = evaluator.evaluate_row(&person, properties, &ctx);
+ assert_eq!(
+ stats.shortcut_evaluations, expected,
+ "{properties} shortcut {} conditions",
+ stats.shortcut_evaluations
+ );
}
}
@@ -929,7 +1555,10 @@ mod tests {
pinned(&[(1, HASH_A), (1, HASH_B)]),
vec![participation(1, leaves, false)],
)));
- let mut evaluator = PersonEvaluator::new(TeamId(2), validated.run.conditions, true);
+ let mut evaluator = PersonEvaluator::new(
+ &Arc::new(validated.run),
+ PersonEmissionPolicy::EveryScannedPerson,
+ );
let ctx = context();
let (outcome, stats) = evaluator.evaluate_row(
diff --git a/rust/cohort-seeder/src/domain/person_analysis.rs b/rust/cohort-seeder/src/domain/person_analysis.rs
new file mode 100644
index 000000000000..84d4930b6bf2
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/person_analysis.rs
@@ -0,0 +1,701 @@
+//! Domain layer: what each of a run's person conditions needs from a scanned row, decided once from
+//! its bytecode. Depends on `person`, `person_relevance`, `projection`, and `cohort-core`.
+//!
+//! # Why a key check can stand in for the VM
+//!
+//! `GET_GLOBAL` is the VM's only path into the globals dict and it takes its path from literal
+//! strings the compiler pushed, so the analyzer's read set is the whole surface a condition can
+//! touch. When every one of those reads is `person.properties.<key>…` or `project.*`, a person whose
+//! blob is a JSON object carrying none of those keys resolves every read to `null` — exactly as `{}`
+//! does, because `GET_GLOBAL` pushes `Null` for a missing key under a present root. The program then
+//! executes the identical instruction sequence, so its outcome on `{}` is its outcome on every such
+//! blob, VM errors included.
+//!
+//! Three shapes stay on the VM. `person.id` and a bare `person.properties` vary per row. A native
+//! that reads how a number was spelled, or bytecode the analyzer could not follow, leaves the read
+//! set unproven. A root no person-scope globals dict carries (`event`, `properties`, `pdi`) raises
+//! `UnknownGlobal` identically on every row and could be shortcut too; it is left to the VM because
+//! proving that costs more than the case is worth.
+//!
+//! # Why the blob must be a JSON object
+//!
+//! A non-object blob is not "an object missing keys". An array errors where an object yields null
+//! (`GET_GLOBAL` coerces the key to a number on an array), and a scalar or a literal `null` yields
+//! null without carrying keys at all. Only the object case is answered here; the rest reach the VM.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use cohort_core::filters::TeamId;
+use cohort_core::hogvm::analysis::{
+ analyze_condition_within, AnalysisBudget, FullColumnsReason, GlobalRoot, Projection, ReadPath,
+ UnanalyzableReason,
+};
+use cohort_core::hogvm::{
+ classify_vm_error, person_scan_globals, CohortEvaluator, ConditionProgram, EvalOutcome,
+ VmErrorClass,
+};
+use serde_json::{Map, Value};
+use uuid::Uuid;
+
+use super::person::EvaluatedConditions;
+use super::person_relevance::{ConditionIndex, TruthVector};
+use super::projection::ProjectedKeys;
+
+/// How many worst-case conditions one person run's analysis may cost, as one budget its conditions
+/// share. Mirrors the behavioral census: per-condition ceilings leave `conditions × ceiling`, and a
+/// shared budget spent in hash order keeps the classification a pure function of the pinned payload,
+/// so a run re-validated on another replica classifies identically.
+const ANALYSIS_WORST_CASE_CONDITIONS: usize = 8;
+
+/// What evaluating one condition against one row came to. Mirrors [`EvalOutcome`] minus the
+/// unclonable error payload, so a cached verdict and a freshly evaluated one produce the same
+/// per-row statistics.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConditionVerdict {
+ Matched(bool),
+ UnknownFunction,
+ VmFailure(VmErrorClass),
+}
+
+impl From<EvalOutcome> for ConditionVerdict {
+ fn from(outcome: EvalOutcome) -> Self {
+ match outcome {
+ EvalOutcome::Matched(matched) => Self::Matched(matched),
+ EvalOutcome::UnknownFunction(_) => Self::UnknownFunction,
+ EvalOutcome::VmError(error) => Self::VmFailure(classify_vm_error(&error)),
+ }
+ }
+}
+
+/// Why a condition has to run on every row.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum AlwaysEvaluateReason {
+ /// Reads `person.id`, which differs on every row.
+ ReadsPersonId,
+ /// Hands a whole `person` or `properties` object somewhere, so which keys decide it is settled
+ /// at run time.
+ WholeObject,
+ /// Calls a native that reads how a number was spelled rather than what it is.
+ RepresentationSensitive,
+ /// Reads a root the person-scope globals do not carry, so the read set says nothing about the
+ /// blob.
+ ForeignRoot,
+ /// The run's shared analysis budget ran out before this condition. The one reason that says to
+ /// raise [`ANALYSIS_WORST_CASE_CONDITIONS`] rather than to accept the wide answer, so it is
+ /// named apart from the rest.
+ BudgetSpent,
+ /// The analyzer lost track of the program.
+ Unanalyzable,
+}
+
+impl AlwaysEvaluateReason {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::ReadsPersonId => "reads_person_id",
+ Self::WholeObject => "whole_object",
+ Self::RepresentationSensitive => "representation_sensitive",
+ Self::ForeignRoot => "foreign_root",
+ Self::BudgetSpent => "budget_spent",
+ Self::Unanalyzable => "unanalyzable",
+ }
+ }
+}
+
+/// What one condition's truth depends on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum RowDependence {
+ /// Every read is `person.properties.<key>…` or `project.*`, so a JSON object carrying none of
+ /// `keys` reaches `vacuous` without the VM.
+ KeyDecidable {
+ keys: BTreeSet<String>,
+ vacuous: ConditionVerdict,
+ },
+ AlwaysEvaluate(AlwaysEvaluateReason),
+}
+
+/// One [`RowDependence`] per surviving condition, in [`EvaluatedConditions`] order.
+#[derive(Debug)]
+pub struct PersonConditionAnalyses(Vec<RowDependence>);
+
+impl PersonConditionAnalyses {
+ /// Classify every surviving condition and, for the key-decidable ones, record the outcome it
+ /// reaches on an empty property bag.
+ ///
+ /// The budget is shared across the run's conditions and spent in their (hash) order, so the
+ /// classification stays a pure function of the pinned payload.
+ pub fn build(team_id: TeamId, conditions: &EvaluatedConditions) -> Self {
+ let mut budget = AnalysisBudget::for_conditions(ANALYSIS_WORST_CASE_CONDITIONS);
+ let mut evaluator = CohortEvaluator::new();
+ evaluator.set_globals(person_scan_globals(
+ team_id,
+ // No key-decidable condition reads `person.id`, so which id stands here cannot reach a
+ // recorded outcome.
+ Uuid::nil(),
+ Value::Object(Map::new()),
+ ));
+
+ let dependences = conditions
+ .iter()
+ .map(|(_, program)| {
+ let analysis = analyze_condition_within(program.tokens(), &mut budget);
+ match decidable_keys(&analysis.projection) {
+ Ok(keys) => RowDependence::KeyDecidable {
+ keys,
+ vacuous: vacuous_outcome(&mut evaluator, program),
+ },
+ Err(reason) => RowDependence::AlwaysEvaluate(reason),
+ }
+ })
+ .collect();
+ Self(dependences)
+ }
+
+ /// The outcome `index` reaches on `object` without the VM, or `None` when it needs one.
+ pub fn shortcut(
+ &self,
+ index: ConditionIndex,
+ object: Option<&Map<String, Value>>,
+ ) -> Option<ConditionVerdict> {
+ let RowDependence::KeyDecidable { keys, vacuous } = self.0.get(index.get())? else {
+ return None;
+ };
+ let object = object?;
+ keys.iter()
+ .all(|key| !object.contains_key(key))
+ .then_some(*vacuous)
+ }
+
+ /// Every key the run's conditions read, when *all* of them are key-decidable — the precondition
+ /// for asking ClickHouse to drop key-less rows. `None` when some condition needs the VM, or when
+ /// the union is empty (which [`ProjectedKeys`] cannot express, and which no filter can narrow).
+ pub fn keys_if_every_condition_is_key_decidable(&self) -> Option<ProjectedKeys> {
+ let mut union = BTreeSet::new();
+ for dependence in &self.0 {
+ match dependence {
+ RowDependence::KeyDecidable { keys, .. } => union.extend(keys.iter().cloned()),
+ RowDependence::AlwaysEvaluate(_) => return None,
+ }
+ }
+ ProjectedKeys::new(union)
+ }
+
+ /// The truth vector every key-less object blob produces, for the scan filter's precondition.
+ ///
+ /// `None` when some condition needs the VM, so no such vector exists — and also when some
+ /// condition's vacuous verdict is a VM failure rather than an answer. That second case matters
+ /// for the same reason the fold refuses to prune an incompletely evaluated row: a condition the
+ /// VM never answered is left out of `evaluated`, so the consumer keeps the bit it already
+ /// stored for that leaf and composes something this vector does not describe. A run holding one
+ /// cannot hand its key test to ClickHouse at all.
+ pub fn vacuous_truths(&self) -> Option<TruthVector> {
+ let mut truths = TruthVector::ABSENT;
+ for (position, dependence) in self.0.iter().enumerate() {
+ let RowDependence::KeyDecidable { vacuous, .. } = dependence else {
+ return None;
+ };
+ let ConditionVerdict::Matched(matched) = vacuous else {
+ return None;
+ };
+ if *matched {
+ truths.set(
+ ConditionIndex::new(position).expect(
+ "one entry per condition, and validation caps those at the wire cap",
+ ),
+ );
+ }
+ }
+ Some(truths)
+ }
+
+ /// Counts per class for the per-run log line.
+ pub fn census(&self) -> PersonAnalysisCensus {
+ let mut census = PersonAnalysisCensus::default();
+ for dependence in &self.0 {
+ match dependence {
+ RowDependence::KeyDecidable { .. } => census.key_decidable += 1,
+ RowDependence::AlwaysEvaluate(reason) => {
+ *census.always_evaluate.entry(*reason).or_default() += 1;
+ }
+ }
+ }
+ census
+ }
+}
+
+/// How a run's conditions classified, rendered into the `person run analyzed` line.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct PersonAnalysisCensus {
+ pub key_decidable: u32,
+ pub always_evaluate: BTreeMap<AlwaysEvaluateReason, u32>,
+}
+
+impl PersonAnalysisCensus {
+ /// `reason=count` pairs, ascending, for the log line.
+ pub fn render_always_evaluate(&self) -> String {
+ self.always_evaluate
+ .iter()
+ .map(|(reason, count)| format!("{}={count}", reason.as_str()))
+ .collect::<Vec<_>>()
+ .join(",")
+ }
+}
+
+/// The top-level `person.properties` keys a projection resolves to, or why it cannot.
+fn decidable_keys(projection: &Projection) -> Result<BTreeSet<String>, AlwaysEvaluateReason> {
+ let paths = match projection {
+ Projection::Reads(paths) => paths,
+ Projection::FullColumns(reason) => {
+ return Err(match reason {
+ FullColumnsReason::BarePropertiesRoot | FullColumnsReason::BarePersonRoot => {
+ AlwaysEvaluateReason::WholeObject
+ }
+ FullColumnsReason::RepresentationSensitiveCall => {
+ AlwaysEvaluateReason::RepresentationSensitive
+ }
+ FullColumnsReason::Unanalyzable(
+ UnanalyzableReason::IterationBudget | UnanalyzableReason::StateBudget,
+ ) => AlwaysEvaluateReason::BudgetSpent,
+ FullColumnsReason::Unanalyzable(_) => AlwaysEvaluateReason::Unanalyzable,
+ })
+ }
+ };
+ let mut keys = BTreeSet::new();
+ for path in paths {
+ keys.extend(decidable_key(path)?);
+ }
+ Ok(keys)
+}
+
+/// The key one read path resolves to: `Some` for `person.properties.<key>…`, `None` for a read whose
+/// value is the same on every row of the run.
+fn decidable_key(path: &ReadPath) -> Result<Option<String>, AlwaysEvaluateReason> {
+ match path.root {
+ // `project.id` is the run's own team, identical on every row.
+ GlobalRoot::Project => Ok(None),
+ GlobalRoot::Person => {
+ let mut segments = path.segments.iter().map(String::as_str);
+ match (segments.next(), segments.next()) {
+ (Some("properties"), Some(key)) => Ok(Some(key.to_owned())),
+ // A bare `person.properties` hands the whole bag somewhere.
+ (Some("properties"), None) => Err(AlwaysEvaluateReason::WholeObject),
+ (Some("id"), _) => Err(AlwaysEvaluateReason::ReadsPersonId),
+ // Any other key under `person` resolves to null on every row, but telling that
+ // apart from a shape this mapping has not met is not worth the risk.
+ _ => Err(AlwaysEvaluateReason::ForeignRoot),
+ }
+ }
+ _ => Err(AlwaysEvaluateReason::ForeignRoot),
+ }
+}
+
+fn vacuous_outcome(
+ evaluator: &mut CohortEvaluator,
+ program: &ConditionProgram,
+) -> ConditionVerdict {
+ evaluator.evaluate_detailed(program).into()
+}
+
+#[cfg(test)]
+mod tests {
+ use cohort_core::hogvm::analysis::analyze_condition;
+ use serde_json::json;
+
+ use super::*;
+
+ /// Bytecode as the cohort compiler emits it, taken from `generate_cohort_filter_bytecode` rather
+ /// than hand-written, so the classification is tested against the shapes production stores.
+ fn compiled(operator: &str) -> Value {
+ match operator {
+ "is_set" => json!([
+ "_H",
+ 1,
+ 31,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 12
+ ]),
+ "not_icontains" => json!([
+ "_H",
+ 1,
+ 32,
+ "%@posthog.com%",
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 2,
+ "toString",
+ 1,
+ 20
+ ]),
+ "exact" => json!([
+ "_H",
+ 1,
+ 32,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 11
+ ]),
+ "in_list" => json!([
+ "_H",
+ 1,
+ 32,
+ "paid",
+ 32,
+ "free",
+ 44,
+ 2,
+ 32,
+ "plan",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 21
+ ]),
+ "not_regex" => json!([
+ "_H",
+ 1,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 2,
+ "toString",
+ 1,
+ 32,
+ "^a.*",
+ 2,
+ "match",
+ 2,
+ 5,
+ 47,
+ 3,
+ 35,
+ 33,
+ 1
+ ]),
+ // `gt`, lowered through `null_safe_comparisons` into an `if`.
+ "gt" => json!([
+ "_H",
+ 1,
+ 32,
+ "age",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 2,
+ "isNull",
+ 1,
+ 33,
+ 21,
+ 2,
+ "isNull",
+ 1,
+ 4,
+ 2,
+ 40,
+ 3,
+ 30,
+ 39,
+ 11,
+ 33,
+ 21,
+ 32,
+ "age",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 13
+ ]),
+ "person_id" => json!(["_H", 1, 32, "x", 32, "id", 32, "person", 1, 2, 11]),
+ "bare_person" => json!(["_H", 1, 32, "person", 1, 1, 2, "jsonStringify", 1, 11]),
+ "typeof" => json!([
+ "_H",
+ 1,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 2,
+ "typeof",
+ 1,
+ 32,
+ "string",
+ 11
+ ]),
+ "project_only" => json!(["_H", 1, 32, "id", 32, "project", 1, 2, 33, 2, 11]),
+ // `person.properties.company.size` — a read two keys deep under `properties`.
+ "nested" => json!([
+ "_H",
+ 1,
+ 32,
+ "big",
+ 32,
+ "size",
+ 32,
+ "company",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 4,
+ 11
+ ]),
+ other => panic!("no fixture for {other}"),
+ }
+ }
+
+ fn dependence(operator: &str) -> RowDependence {
+ let bytecode = compiled(operator);
+ let tokens = bytecode.as_array().expect("fixtures are arrays");
+ let analysis = analyze_condition(tokens);
+ match decidable_keys(&analysis.projection) {
+ Ok(keys) => {
+ let program = ConditionProgram::from_stored(tokens).expect("fixtures load");
+ let mut evaluator = CohortEvaluator::new();
+ evaluator.set_globals(person_scan_globals(
+ TeamId(2),
+ Uuid::nil(),
+ Value::Object(Map::new()),
+ ));
+ RowDependence::KeyDecidable {
+ keys,
+ vacuous: vacuous_outcome(&mut evaluator, &program),
+ }
+ }
+ Err(reason) => RowDependence::AlwaysEvaluate(reason),
+ }
+ }
+
+ fn key_decidable(operator: &str) -> (BTreeSet<String>, ConditionVerdict) {
+ match dependence(operator) {
+ RowDependence::KeyDecidable { keys, vacuous } => (keys, vacuous),
+ other => panic!("{operator} classified as {other:?}"),
+ }
+ }
+
+ fn keys(names: &[&str]) -> BTreeSet<String> {
+ names.iter().map(|name| (*name).to_owned()).collect()
+ }
+
+ /// The vacuous truths are what the whole optimization turns on: `is_set` is false on a person
+ /// with no email and `not_icontains` is *true*, because the VM prints a missing property as the
+ /// string "null" before the NOT ILIKE. Reading either the wrong way would prune members.
+ #[test]
+ fn the_compiled_person_operators_are_key_decidable_with_the_vm_s_own_vacuous_truth() {
+ assert_eq!(
+ key_decidable("is_set"),
+ (keys(&["email"]), ConditionVerdict::Matched(false))
+ );
+ assert_eq!(
+ key_decidable("not_icontains"),
+ (keys(&["email"]), ConditionVerdict::Matched(true))
+ );
+ assert_eq!(
+ key_decidable("exact"),
+ (keys(&["email"]), ConditionVerdict::Matched(false))
+ );
+ assert_eq!(
+ key_decidable("in_list"),
+ (keys(&["plan"]), ConditionVerdict::Matched(false))
+ );
+ assert_eq!(
+ key_decidable("not_regex"),
+ (keys(&["email"]), ConditionVerdict::Matched(true))
+ );
+ assert_eq!(
+ key_decidable("gt"),
+ (keys(&["age"]), ConditionVerdict::Matched(false))
+ );
+ // A condition reading only the team reads nothing per row, so it is decidable with no keys.
+ assert_eq!(
+ key_decidable("project_only"),
+ (BTreeSet::new(), ConditionVerdict::Matched(true))
+ );
+ // A nested read claims its *top-level* key, because that is the only thing
+ // `JSONExtractKeys` can see. Claiming `size` instead would render a filter that drops every
+ // person carrying `company` while believing it filtered on `size`.
+ assert_eq!(
+ key_decidable("nested"),
+ (keys(&["company"]), ConditionVerdict::Matched(false))
+ );
+ }
+
+ #[test]
+ fn row_varying_and_unprovable_reads_stay_on_the_vm() {
+ assert_eq!(
+ dependence("person_id"),
+ RowDependence::AlwaysEvaluate(AlwaysEvaluateReason::ReadsPersonId)
+ );
+ assert_eq!(
+ dependence("bare_person"),
+ RowDependence::AlwaysEvaluate(AlwaysEvaluateReason::WholeObject)
+ );
+ assert_eq!(
+ dependence("typeof"),
+ RowDependence::AlwaysEvaluate(AlwaysEvaluateReason::RepresentationSensitive)
+ );
+ }
+
+ /// The shortcut must fire only on an object missing *every* key, and never on a non-object: an
+ /// array makes `GET_GLOBAL` coerce a string key to a number and error where `{}` yields null.
+ #[test]
+ fn the_shortcut_fires_only_on_an_object_missing_every_key() {
+ let analyses = PersonConditionAnalyses(vec![RowDependence::KeyDecidable {
+ keys: keys(&["email", "plan"]),
+ vacuous: ConditionVerdict::Matched(true),
+ }]);
+ let index = ConditionIndex::new(0).unwrap();
+ let object = |text: &str| match serde_json::from_str::<Value>(text).unwrap() {
+ Value::Object(map) => Some(map),
+ _ => None,
+ };
+
+ for missing in [
+ r#"{}"#,
+ r#"{"other":1}"#,
+ r#"{"Email":"x"}"#,
+ r#"{"a":{"email":1}}"#,
+ ] {
+ assert_eq!(
+ analyses.shortcut(index, object(missing).as_ref()),
+ Some(ConditionVerdict::Matched(true)),
+ "{missing} carries none of the keys"
+ );
+ }
+ for present in [
+ r#"{"email":null}"#,
+ r#"{"plan":"paid"}"#,
+ r#"{"email":"a"}"#,
+ ] {
+ assert_eq!(
+ analyses.shortcut(index, object(present).as_ref()),
+ None,
+ "{present} carries a key, so the VM decides it"
+ );
+ }
+ assert_eq!(analyses.shortcut(index, None), None, "a non-object blob");
+ }
+
+ #[test]
+ fn a_condition_needing_the_vm_withdraws_the_scan_filter_and_the_vacuous_vector() {
+ let mixed = PersonConditionAnalyses(vec![
+ RowDependence::KeyDecidable {
+ keys: keys(&["email"]),
+ vacuous: ConditionVerdict::Matched(true),
+ },
+ RowDependence::AlwaysEvaluate(AlwaysEvaluateReason::ReadsPersonId),
+ ]);
+ assert_eq!(mixed.keys_if_every_condition_is_key_decidable(), None);
+ assert_eq!(mixed.vacuous_truths(), None);
+
+ let decidable = PersonConditionAnalyses(vec![
+ RowDependence::KeyDecidable {
+ keys: keys(&["email"]),
+ vacuous: ConditionVerdict::Matched(false),
+ },
+ RowDependence::KeyDecidable {
+ keys: keys(&["plan"]),
+ vacuous: ConditionVerdict::Matched(true),
+ },
+ ]);
+ let scan_keys = decidable
+ .keys_if_every_condition_is_key_decidable()
+ .expect("both conditions are key-decidable");
+ assert_eq!(scan_keys.iter().collect::<Vec<_>>(), ["email", "plan"]);
+
+ let truths = decidable.vacuous_truths().expect("both are key-decidable");
+ assert!(!truths.get(ConditionIndex::new(0).unwrap()));
+ assert!(truths.get(ConditionIndex::new(1).unwrap()));
+ }
+
+ /// An empty key union cannot be expressed as a scan filter, so the run scans wide and prunes
+ /// per row instead of rendering `hasAny(keys, [])`, which drops every object.
+ #[test]
+ fn a_condition_reading_no_keys_renders_no_scan_filter() {
+ let analyses = PersonConditionAnalyses(vec![RowDependence::KeyDecidable {
+ keys: BTreeSet::new(),
+ vacuous: ConditionVerdict::Matched(true),
+ }]);
+ assert_eq!(analyses.keys_if_every_condition_is_key_decidable(), None);
+ }
+
+ /// The exactness claim, run through the real VM: for a key-decidable condition, any object blob
+ /// lacking its keys evaluates to the cached outcome, and a blob carrying one is sent to the VM.
+ #[test]
+ fn the_cached_vacuous_outcome_matches_the_vm_on_every_key_less_object() {
+ for operator in [
+ "is_set",
+ "not_icontains",
+ "exact",
+ "in_list",
+ "not_regex",
+ "gt",
+ ] {
+ let bytecode = compiled(operator);
+ let tokens = bytecode.as_array().unwrap();
+ let program = ConditionProgram::from_stored(tokens).unwrap();
+ let (keys, vacuous) = key_decidable(operator);
+
+ for blob in [
+ json!({}),
+ json!({ "unrelated": 1 }),
+ json!({ "Email": "[email protected]", "PLAN": "paid", "AGE": 99 }),
+ json!({ "nested": { "email": "[email protected]" } }),
+ json!({ "emai": "[email protected]", "emails": ["[email protected]"] }),
+ ] {
+ let map = blob.as_object().unwrap();
+ assert!(
+ keys.iter().all(|key| !map.contains_key(key)),
+ "{blob} was meant to carry none of {keys:?}"
+ );
+ let mut evaluator = CohortEvaluator::new();
+ evaluator.set_globals(person_scan_globals(
+ TeamId(2),
+ Uuid::from_u128(7),
+ blob.clone(),
+ ));
+ assert_eq!(
+ vacuous_outcome(&mut evaluator, &program),
+ vacuous,
+ "{operator} on {blob} diverged from its cached vacuous outcome"
+ );
+ }
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/person_relevance.rs b/rust/cohort-seeder/src/domain/person_relevance.rs
new file mode 100644
index 000000000000..2eb9a32cd6f6
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/person_relevance.rs
@@ -0,0 +1,610 @@
+//! Domain layer: whether one scanned person's leaf truths can change a participating cohort's
+//! membership at all. Depends on `person`'s [`EvaluatedConditions`] and `cohort-core`'s filter
+//! trees; reaches nothing outside `domain`.
+//!
+//! # Why an absent prior is the baseline
+//!
+//! A person seed reaches membership only through the leaf bits it asserts: the consumer stores
+//! `matched ∪ (stored \ evaluated)` and re-walks each cohort's tree over the result. So a person
+//! whose truth vector reaches the same verdict as the all-false vector contributes nothing, and
+//! emitting them buys a record write and a recompose that ends unchanged.
+//!
+//! The baseline is the *absent* prior rather than the stored one, which the seeder cannot see. That
+//! is the trade the non-matcher skip already makes one level up — a person whose every leaf is
+//! false is skipped today, so a stale stored TRUE for them already survives a run. Pruning widens
+//! that from all-false vectors to vacuous ones. The healer cadence retracts both, and it prunes
+//! nothing.
+//!
+//! # Scope: the run's own participations
+//!
+//! The oracle is built from the `TeamFilters` validation assembles out of this run's *active*
+//! participations, so "a participating cohort" is literal. The consumer's recompose fan-out is by
+//! leaf state key and reaches every cohort on the team holding that leaf, so a person pruned here
+//! can still be one a non-participating cohort would have gained from the same seed. That healing
+//! was a side effect of seeding everyone, never a promise: a cohort's readiness only ever came from
+//! its own run. Stopping it is the point, not an oversight.
+//!
+//! # The tree is part of the contract
+//!
+//! What a run stores is valid for the trees it pinned: a person pruned under `AND(a, b)` has no
+//! record for a later `OR(a, b)` to read, and the consumer reads an absent leaf as false. Django
+//! therefore re-runs the person kind whenever the tree as this oracle sees it moves
+//! (`FilterShapeHashes::composition_repair_kinds` in `products/cohorts/backend/models/leaf_shape.py`),
+//! and the finalizer refuses to stamp a person run that predates such an edit.
+//!
+//! # Why three-valued logic
+//!
+//! A run pins only its person conditions. Behavioral leaves, cohort references, and person leaves
+//! the run did not pin are `Unknown` here. Kleene's strong three-valued logic (a `False` under AND
+//! and a `True` under OR win over an unknown; an unknown wins over everything else) is sound for
+//! that: a determinate K3 result holds for *every* substitution of the unknowns, so two
+//! determinate, equal results mean the cohort's verdict cannot move whatever the unknowns are. An
+//! `Unknown` on either side emits.
+
+use std::collections::HashMap;
+
+use cohort_core::eligibility::{CohortEligibility, ExcludedReason};
+use cohort_core::filters::tree::{BoolOp, CohortLeaf, FilterNode};
+use cohort_core::filters::TeamFilters;
+use cohort_core::seed::MAX_PERSON_SEED_HASHES;
+
+use super::person::EvaluatedConditions;
+
+/// One condition's position in [`EvaluatedConditions`], which is sorted-distinct by hash — so
+/// walking indices ascending walks hashes ascending, which is the order a seed's `evaluated` list
+/// has to be in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct ConditionIndex(u16);
+
+impl ConditionIndex {
+ /// `None` past the wire cap, which validation already refuses — so this is the type restating
+ /// that cap rather than a second policy.
+ pub fn new(position: usize) -> Option<Self> {
+ if position >= MAX_PERSON_SEED_HASHES {
+ return None;
+ }
+ u16::try_from(position).ok().map(Self)
+ }
+
+ pub const fn get(self) -> usize {
+ self.0 as usize
+ }
+}
+
+const TRUTH_WORDS: usize = MAX_PERSON_SEED_HASHES / u64::BITS as usize;
+// The division above truncates, which would silently shorten the vector rather than fail.
+const _: () = assert!(MAX_PERSON_SEED_HASHES.is_multiple_of(u64::BITS as usize));
+
+/// Which of a run's conditions matched TRUE on one scanned person. Every other outcome — matched
+/// FALSE, an unknown native, a VM error — reads FALSE here, which is what the consumer reads for a
+/// hash absent from `matched`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct TruthVector([u64; TRUTH_WORDS]);
+
+impl TruthVector {
+ /// The vector of a person with no stored record: every leaf false.
+ pub const ABSENT: Self = Self([0; TRUTH_WORDS]);
+
+ pub fn set(&mut self, index: ConditionIndex) {
+ let position = index.get();
+ self.0[position / 64] |= 1 << (position % 64);
+ }
+
+ pub fn get(&self, index: ConditionIndex) -> bool {
+ let position = index.get();
+ self.0[position / 64] & (1 << (position % 64)) != 0
+ }
+}
+
+/// Kleene's strong three-valued truth.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Truth3 {
+ False,
+ True,
+ Unknown,
+}
+
+impl Truth3 {
+ const fn of(value: bool) -> Self {
+ if value {
+ Self::True
+ } else {
+ Self::False
+ }
+ }
+}
+
+/// A participation's tree compiled against the run's pinned conditions: a person leaf the run
+/// evaluates is [`RelevanceNode::Pinned`], everything else is [`RelevanceNode::Unknown`].
+#[derive(Debug)]
+enum RelevanceNode {
+ /// Empty is `True`, matching the consumer's own `all` fold over an empty group.
+ And(Vec<Self>),
+ /// Empty is `False`, matching its `any` fold.
+ Or(Vec<Self>),
+ Pinned {
+ index: ConditionIndex,
+ negated: bool,
+ },
+ /// A behavioral leaf, a cohort reference, or a person leaf this run did not pin. Negation is
+ /// absent on purpose: `NOT Unknown` is `Unknown`.
+ Unknown,
+}
+
+impl RelevanceNode {
+ /// The three-valued lift of the consumer's `stage2::evaluate_tree`, which this crate cannot
+ /// call: `cohort-seeder` does not depend on `cohort-stream-processor`. Four identities have to
+ /// agree, and today they do only by inspection — AND is `all` (so an empty group is `True`), OR
+ /// is `any` (empty is `False`), a leaf is its bit `^ negated`, and an absent leaf is `false`.
+ /// A cohort-reference leaf collapses to [`Self::Unknown`] and drops its negation bit, which is
+ /// sound only because `NOT Unknown` is `Unknown`.
+ ///
+ /// No test binds this to the consumer's fold. Closing that needs a test in the consumer's own
+ /// crate, because the edge has to point that way.
+ fn evaluate(&self, truths: &TruthVector) -> Truth3 {
+ match self {
+ Self::And(children) => children
+ .iter()
+ .fold(Truth3::True, |acc, child| and3(acc, child.evaluate(truths))),
+ Self::Or(children) => children
+ .iter()
+ .fold(Truth3::False, |acc, child| or3(acc, child.evaluate(truths))),
+ Self::Pinned { index, negated } => Truth3::of(truths.get(*index) ^ negated),
+ Self::Unknown => Truth3::Unknown,
+ }
+ }
+
+ fn compile(node: &FilterNode, by_hash: &HashMap<[u8; 16], ConditionIndex>) -> Self {
+ match node {
+ FilterNode::Group { op, children } => {
+ let children = children
+ .iter()
+ .map(|child| Self::compile(child, by_hash))
+ .collect();
+ match op {
+ BoolOp::And => Self::And(children),
+ BoolOp::Or => Self::Or(children),
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::PersonProperty(leaf)) => {
+ match by_hash.get(&leaf.condition_hash) {
+ Some(index) => Self::Pinned {
+ index: *index,
+ negated: leaf.negated,
+ },
+ None => Self::Unknown,
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::Behavioral(_) | CohortLeaf::CohortRef(_)) => Self::Unknown,
+ }
+ }
+}
+
+const fn and3(left: Truth3, right: Truth3) -> Truth3 {
+ match (left, right) {
+ (Truth3::False, _) | (_, Truth3::False) => Truth3::False,
+ (Truth3::Unknown, _) | (_, Truth3::Unknown) => Truth3::Unknown,
+ (Truth3::True, Truth3::True) => Truth3::True,
+ }
+}
+
+const fn or3(left: Truth3, right: Truth3) -> Truth3 {
+ match (left, right) {
+ (Truth3::True, _) | (_, Truth3::True) => Truth3::True,
+ (Truth3::Unknown, _) | (_, Truth3::Unknown) => Truth3::Unknown,
+ (Truth3::False, Truth3::False) => Truth3::False,
+ }
+}
+
+/// Whether a person's seed can move any participating cohort's verdict.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Relevance {
+ CanChangeSomeCohort,
+ IrrelevantToEveryCohort,
+}
+
+/// One cohort's tree beside the verdict it reaches on [`TruthVector::ABSENT`]. The baseline is
+/// determinate by construction: a cohort whose baseline is `Unknown` can never be proven
+/// irrelevant, so it collapses the oracle to [`RelevanceOracle::AlwaysRelevant`] at build.
+#[derive(Debug)]
+struct CohortRelevance {
+ root: RelevanceNode,
+ baseline: bool,
+}
+
+/// The run's composable participations, compiled once at validation.
+#[derive(Debug)]
+pub struct RelevanceOracle(Verdicts);
+
+#[derive(Debug)]
+enum Verdicts {
+ /// Some composable cohort's verdict is already unknown on the absent vector, so no person can
+ /// be proven irrelevant and every scanned person is emitted.
+ AlwaysRelevant,
+ /// One entry per composable participation. Empty means the run composes nothing, in which case
+ /// no seed can change membership — which is the truth, and the per-run log line reports it.
+ ByCohort(Vec<CohortRelevance>),
+}
+
+impl RelevanceOracle {
+ pub fn build(filters: &TeamFilters, conditions: &EvaluatedConditions) -> Self {
+ let by_hash: HashMap<[u8; 16], ConditionIndex> = conditions
+ .iter()
+ .enumerate()
+ .filter_map(|(position, (hash, _))| {
+ ConditionIndex::new(position).map(|index| (hash.as_bytes(), index))
+ })
+ .collect();
+
+ Self::from_roots(filters.cohorts.iter().filter_map(|(cohort_id, tree)| {
+ let eligibility = filters
+ .eligibility
+ .get(cohort_id)
+ .copied()
+ // A parsed cohort always carries an eligibility entry; an absent one composes.
+ .unwrap_or(CohortEligibility::Stage2Composable);
+ match composability(eligibility) {
+ Composability::NeverComposed => None,
+ Composability::Composable => Some(RelevanceNode::compile(&tree.root, &by_hash)),
+ }
+ }))
+ }
+
+ /// Pair each root with its absent-vector verdict, collapsing to [`Self::AlwaysRelevant`] as
+ /// soon as one of them is indeterminate.
+ fn from_roots(roots: impl IntoIterator<Item = RelevanceNode>) -> Self {
+ let mut cohorts = Vec::new();
+ for root in roots {
+ let baseline = match root.evaluate(&TruthVector::ABSENT) {
+ Truth3::True => true,
+ Truth3::False => false,
+ Truth3::Unknown => return Self(Verdicts::AlwaysRelevant),
+ };
+ cohorts.push(CohortRelevance { root, baseline });
+ }
+ Self(Verdicts::ByCohort(cohorts))
+ }
+
+ /// Judge one person's truths. One walk of each composable participation's tree — the absent
+ /// verdict each is compared against was computed at build. A per-chunk memo over distinct
+ /// vectors was considered and dropped: hashing the 128-byte key costs about what the walk does
+ /// at the tree sizes a person run carries.
+ pub fn judge(&self, truths: &TruthVector) -> Relevance {
+ let cohorts = match &self.0 {
+ Verdicts::AlwaysRelevant => return Relevance::CanChangeSomeCohort,
+ Verdicts::ByCohort(cohorts) => cohorts,
+ };
+ let moved = cohorts
+ .iter()
+ .any(|cohort| cohort.root.evaluate(truths) != Truth3::of(cohort.baseline));
+ match moved {
+ true => Relevance::CanChangeSomeCohort,
+ false => Relevance::IrrelevantToEveryCohort,
+ }
+ }
+
+ /// How many participations the oracle walks, or `None` when it proves nothing. For the per-run
+ /// log line.
+ pub fn composable_cohorts(&self) -> Option<usize> {
+ match &self.0 {
+ Verdicts::AlwaysRelevant => None,
+ Verdicts::ByCohort(cohorts) => Some(cohorts.len()),
+ }
+ }
+}
+
+/// Whether the *consumer* composes a cohort of this class at all.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Composability {
+ NeverComposed,
+ Composable,
+}
+
+/// The seeder freezes its catalog with cascade off, so every ref-bearing cohort reads
+/// `Excluded(HasCohortRef)` here while the consumer runs with cascade on and composes it. The
+/// seeder also holds only the run's own participations, never the referenced cohorts, so
+/// `CycleDetected` and `UnresolvedRef` cannot be trusted either. Only the structural exclusions —
+/// decided from the tree and the parse flags alone — classify identically in both services.
+///
+/// Exhaustive rather than defaulted: a new eligibility variant has to decide here rather than
+/// silently join the class whose members are pruned away.
+const fn composability(eligibility: CohortEligibility) -> Composability {
+ match eligibility {
+ CohortEligibility::SingleLeaf(_)
+ | CohortEligibility::Stage2Composable
+ | CohortEligibility::Stage2ComposableRef => Composability::Composable,
+ CohortEligibility::Excluded(reason) => match reason {
+ ExcludedReason::NotMultiLeaf
+ | ExcludedReason::TopLevelNegation
+ | ExcludedReason::EmptyGroup
+ | ExcludedReason::HasDroppedLeaf => Composability::NeverComposed,
+ ExcludedReason::HasCohortRef
+ | ExcludedReason::CycleDetected
+ | ExcludedReason::UnresolvedRef => Composability::Composable,
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use proptest::prelude::*;
+
+ use super::*;
+
+ fn index(position: usize) -> ConditionIndex {
+ ConditionIndex::new(position).expect("test positions are under the cap")
+ }
+
+ fn vector(bits: &[bool]) -> TruthVector {
+ let mut truths = TruthVector::ABSENT;
+ for (position, bit) in bits.iter().enumerate() {
+ if *bit {
+ truths.set(index(position));
+ }
+ }
+ truths
+ }
+
+ fn pinned(position: usize) -> RelevanceNode {
+ RelevanceNode::Pinned {
+ index: index(position),
+ negated: false,
+ }
+ }
+
+ /// The shape this whole change exists for: `email is_set AND email not_icontains '@posthog.com'`
+ /// with the run pinning both leaves. Only a person carrying a non-PostHog address can move it.
+ #[test]
+ fn an_and_of_a_positive_and_a_vacuously_true_leaf_prunes_everyone_but_its_members() {
+ let oracle = RelevanceOracle::from_roots([RelevanceNode::And(vec![pinned(0), pinned(1)])]);
+
+ // No email: is_set false, not_icontains vacuously true.
+ assert_eq!(
+ oracle.judge(&vector(&[false, true])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ // A @posthog.com address: is_set true, not_icontains false.
+ assert_eq!(
+ oracle.judge(&vector(&[true, false])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ // A member.
+ assert_eq!(
+ oracle.judge(&vector(&[true, true])),
+ Relevance::CanChangeSomeCohort
+ );
+ }
+
+ /// The same two leaves under an OR are a whole-team cohort, so the vacuous vector is exactly the
+ /// one that must not be pruned.
+ #[test]
+ fn an_or_carrying_the_vacuous_leaf_never_prunes_the_vacuous_vector() {
+ let oracle = RelevanceOracle::from_roots([RelevanceNode::Or(vec![pinned(0), pinned(1)])]);
+
+ assert_eq!(
+ oracle.judge(&vector(&[false, true])),
+ Relevance::CanChangeSomeCohort
+ );
+ assert_eq!(
+ oracle.judge(&vector(&[false, false])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ }
+
+ /// An unknown leaf beside a false one still folds to a determinate FALSE, which is what lets a
+ /// cohort mixing behavioral and person leaves prune at all. Under an OR the baseline itself is
+ /// unknown and the oracle stops pruning entirely.
+ #[test]
+ fn an_unknown_leaf_prunes_under_an_and_and_blocks_under_an_or() {
+ let mixed = RelevanceOracle::from_roots([RelevanceNode::And(vec![
+ RelevanceNode::Unknown,
+ pinned(0),
+ pinned(1),
+ ])]);
+ assert_eq!(
+ mixed.judge(&vector(&[false, true])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ assert_eq!(
+ mixed.judge(&vector(&[true, true])),
+ Relevance::CanChangeSomeCohort,
+ "the person arm now carries the composition, so the seed has to reach the consumer"
+ );
+
+ let unknown_baseline = RelevanceOracle::from_roots([RelevanceNode::Or(vec![
+ RelevanceNode::Unknown,
+ pinned(0),
+ ])]);
+ assert_eq!(
+ unknown_baseline.composable_cohorts(),
+ None,
+ "an indeterminate baseline collapses the oracle"
+ );
+ assert_eq!(
+ unknown_baseline.judge(&vector(&[false])),
+ Relevance::CanChangeSomeCohort
+ );
+ }
+
+ /// A negated person leaf reads `bit ^ negated`, the consumer's own rule, so an absent prior
+ /// makes it TRUE and a matching person makes it FALSE.
+ #[test]
+ fn a_negated_pinned_leaf_inverts_the_bit() {
+ let oracle = RelevanceOracle::from_roots([RelevanceNode::And(vec![
+ pinned(0),
+ RelevanceNode::Pinned {
+ index: index(1),
+ negated: true,
+ },
+ ])]);
+
+ assert_eq!(
+ oracle.judge(&vector(&[true, false])),
+ Relevance::CanChangeSomeCohort
+ );
+ assert_eq!(
+ oracle.judge(&vector(&[true, true])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ }
+
+ /// The fold accumulators, which every group uses and the empty group exposes directly: AND
+ /// starts at TRUE and OR at FALSE, matching the consumer's `all`/`any`. Flipping either would
+ /// invert every group in the oracle.
+ ///
+ /// Note this is not a test about `EmptyGroup` cohorts. Those classify as
+ /// `Excluded(EmptyGroup)`, which `composability` calls never-composed, so `build` never compiles
+ /// one and the empty arms are unreachable through it.
+ #[test]
+ fn the_group_fold_accumulators_match_the_consumers() {
+ assert_eq!(
+ RelevanceNode::And(Vec::new()).evaluate(&TruthVector::ABSENT),
+ Truth3::True
+ );
+ assert_eq!(
+ RelevanceNode::Or(Vec::new()).evaluate(&TruthVector::ABSENT),
+ Truth3::False
+ );
+ }
+
+ /// A run composing nothing prunes everyone, which is correct — no participation registers
+ /// membership — and is why the per-run log line reports the count.
+ #[test]
+ fn an_oracle_with_no_composable_cohort_prunes_every_vector() {
+ let empty = RelevanceOracle::from_roots([]);
+ assert_eq!(empty.composable_cohorts(), Some(0));
+ assert_eq!(
+ empty.judge(&vector(&[true, true])),
+ Relevance::IrrelevantToEveryCohort
+ );
+ }
+
+ /// Only the structural exclusions are decided the same way in both services; the seeder freezes
+ /// with cascade off, so a ref-bearing cohort it calls excluded is one the consumer composes.
+ #[test]
+ fn only_structurally_excluded_cohorts_count_as_never_composed() {
+ use cohort_core::LeafStateKey;
+
+ for eligibility in [
+ CohortEligibility::Excluded(ExcludedReason::NotMultiLeaf),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ ] {
+ assert_eq!(composability(eligibility), Composability::NeverComposed);
+ }
+ for eligibility in [
+ CohortEligibility::SingleLeaf(LeafStateKey([0; 16])),
+ CohortEligibility::Stage2Composable,
+ CohortEligibility::Stage2ComposableRef,
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ ] {
+ assert_eq!(composability(eligibility), Composability::Composable);
+ }
+ }
+
+ /// The bit positions must not alias across the 64-bit word boundary, which a `1 << position`
+ /// written without the word split would do silently past index 63.
+ #[test]
+ fn truth_vector_bits_are_independent_across_word_boundaries() {
+ const POSITIONS: [usize; 7] = [0, 1, 63, 64, 65, 127, MAX_PERSON_SEED_HASHES - 1];
+ for position in POSITIONS {
+ let mut truths = TruthVector::ABSENT;
+ truths.set(index(position));
+ for other in POSITIONS {
+ assert_eq!(
+ truths.get(index(other)),
+ other == position,
+ "setting {position} answered {other}"
+ );
+ }
+ }
+ assert_eq!(ConditionIndex::new(MAX_PERSON_SEED_HASHES), None);
+ }
+
+ /// The two-valued evaluation the consumer performs once the unknowns are filled in. Both
+ /// branches of every group are evaluated so the unknown cursor advances identically whatever the
+ /// truths are — a short-circuiting walk would hand the two sides different fillings.
+ fn evaluate_completed(
+ node: &RelevanceNode,
+ truths: TruthVector,
+ filling: &[bool],
+ cursor: &mut usize,
+ ) -> bool {
+ match node {
+ RelevanceNode::And(children) => children.iter().fold(true, |acc, child| {
+ acc & evaluate_completed(child, truths, filling, cursor)
+ }),
+ RelevanceNode::Or(children) => children.iter().fold(false, |acc, child| {
+ acc | evaluate_completed(child, truths, filling, cursor)
+ }),
+ RelevanceNode::Pinned { index, negated } => truths.get(*index) ^ negated,
+ RelevanceNode::Unknown => {
+ let bit = filling[*cursor % filling.len()];
+ *cursor += 1;
+ bit
+ }
+ }
+ }
+
+ const PROPTEST_LEAVES: usize = 4;
+
+ fn arb_node(depth: u32) -> impl Strategy<Value = RelevanceNode> {
+ let leaf = (0..PROPTEST_LEAVES, any::<bool>(), any::<bool>()).prop_map(
+ |(position, negated, unknown)| match unknown {
+ true => RelevanceNode::Unknown,
+ false => RelevanceNode::Pinned {
+ index: index(position),
+ negated,
+ },
+ },
+ );
+ leaf.prop_recursive(depth, 16, 3, |inner| {
+ prop_oneof![
+ prop::collection::vec(inner.clone(), 0..3).prop_map(RelevanceNode::And),
+ prop::collection::vec(inner, 0..3).prop_map(RelevanceNode::Or),
+ ]
+ })
+ }
+
+ proptest! {
+ /// The soundness law the pruning rests on: when the oracle calls a vector irrelevant, the
+ /// cohort's *two-valued* verdict at that vector equals its verdict at the absent vector, for
+ /// every filling of the unknown leaves. A wrong K3 rule (`NOT Unknown = False`, an AND that
+ /// loses a `False` to an `Unknown`, an OR identity slip) breaks this.
+ #[test]
+ fn an_irrelevant_vector_cannot_move_a_cohort_under_any_completion(
+ root in arb_node(3),
+ bits in prop::collection::vec(any::<bool>(), PROPTEST_LEAVES),
+ fillings in prop::collection::vec(
+ prop::collection::vec(any::<bool>(), 1..16),
+ 1..8,
+ ),
+ ) {
+ let truths = vector(&bits);
+ let oracle = RelevanceOracle::from_roots([root]);
+ // An unknown baseline never prunes, so there is nothing to falsify: reject the case
+ // rather than count it as a pass.
+ prop_assume!(matches!(oracle.0, Verdicts::ByCohort(_)));
+ let Verdicts::ByCohort(cohorts) = &oracle.0 else { unreachable!() };
+ prop_assume!(oracle.judge(&truths) == Relevance::IrrelevantToEveryCohort);
+
+ for cohort in cohorts {
+ for filling in &fillings {
+ let at_truths =
+ evaluate_completed(&cohort.root, truths, filling, &mut 0);
+ let at_absent =
+ evaluate_completed(&cohort.root, TruthVector::ABSENT, filling, &mut 0);
+ prop_assert_eq!(
+ at_truths,
+ at_absent,
+ "pruned a vector that moves the cohort under filling {:?}",
+ filling
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index 1992fa5d00e0..38417eacf3c4 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -324,6 +324,10 @@ fn log_startup(config: &Config) {
persons_per_chunk = config.seeder_persons_per_chunk,
person_max_concurrent_chunks = config.seeder_person_max_concurrent_chunks,
person_emit_nonmatchers = config.seeder_person_emit_nonmatchers,
+ person_emission = cohort_seeder::domain::PersonEmissionPolicy::from_emit_nonmatchers(
+ config.seeder_person_emit_nonmatchers,
+ )
+ .as_str(),
scan_shadow_compare = config.seeder_scan_shadow_compare,
reconcile_auto_dispatch_enabled = config.seeder_reconcile_auto_dispatch_enabled,
confirm_register_backfilled = config.seeder_confirm_register_backfilled,
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 958908388543..21582a36f5ca 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -169,6 +169,23 @@ pub const PERSONS_SCANNED: &str = "seeder_persons_scanned_total";
pub const PERSON_SEEDS_PRODUCED: &str = "seeder_person_seeds_produced_total";
pub const PERSON_NONMATCHERS_SKIPPED: &str = "seeder_person_nonmatchers_skipped_total";
pub const PERSON_ROWS_SKIPPED: &str = "seeder_person_rows_skipped_total";
+/// Scanned persons the fold declined to seed because their leaf truths cannot move a participating
+/// cohort's verdict, labelled by `reason`. Distinct from [`PERSON_NONMATCHERS_SKIPPED`], which keeps
+/// counting only the all-false rows.
+///
+/// Counts the fold's share of the saving only, and **falls** when the scan filter is doing its job:
+/// a row ClickHouse drops never reaches the fold, so it increments neither this nor
+/// [`PERSONS_SCANNED`]. Read it beside [`PERSON_SCAN_FILTER`], which is what separates "this run
+/// cannot be filtered, so the fold prunes" from "the filter applied, so there was little left to
+/// prune". A run reading zero on both is a run that pruned nothing.
+pub const PERSON_ROWS_PRUNED: &str = "seeder_person_rows_pruned_total";
+/// The one `reason` [`PERSON_ROWS_PRUNED`] carries today. A second one joins `prime_zero_series`.
+pub const PRUNE_REASON_IRRELEVANT: &str = "irrelevant";
+/// Conditions decided from the run's cached vacuous verdict rather than by running the VM. Read
+/// against `persons_scanned × conditions` to see how much of the per-row VM cost is gone.
+pub const PERSON_CONDITIONS_SHORTCUT: &str = "seeder_person_conditions_shortcut_total";
+/// One per person chunk, labelled by what became of the run's key filter on it.
+pub const PERSON_SCAN_FILTER: &str = "seeder_person_scan_filter_total";
pub const PERSON_HOGVM_ERRORS: &str = "seeder_person_hogvm_errors_total";
pub const PERSON_BOUNDARIES_PLANNED: &str = "seeder_person_boundaries_planned_total";
/// One run's person planning pass, end to end: the ClickHouse boundaries scan plus the Postgres
diff --git a/rust/cohort-seeder/tests/ch_person_key_filter.rs b/rust/cohort-seeder/tests/ch_person_key_filter.rs
new file mode 100644
index 000000000000..02437e23bef5
--- /dev/null
+++ b/rust/cohort-seeder/tests/ch_person_key_filter.rs
@@ -0,0 +1,305 @@
+//! Proves against a real ClickHouse that the person scan's key-presence filter drops only rows the
+//! seeder's fold would have pruned anyway.
+//!
+//! The filter is the one place where a server-side function decides whether a person is scanned at
+//! all, so a blob ClickHouse reads differently from `serde_json` is a silently dropped member. Only
+//! ClickHouse can say how `JSONType` and `JSONExtractKeys` read a hostile blob, so there is no Rust
+//! mock of the predicate here — a mock would prove the mock.
+//!
+//! The oracle is deliberately loose in one direction and exact in the other. A blob ClickHouse
+//! reports as a JSON object must be dropped exactly when it carries none of the keys, because that
+//! is the whole saving. Every other blob must be admitted, because the seeder decides those: an
+//! array errors in the VM, a scalar and a literal `null` read every key as null, an empty blob
+//! parses to `{}` and is decided from the cached vacuous verdict, a malformed blob is a skipped
+//! row, and a document holding a number ClickHouse cannot represent also reports `Null` while
+//! `serde_json` parses it and the VM reads its keys.
+//!
+//! 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 key 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::person_sql::{person_scan_sql, PersonScanSpec};
+use cohort_seeder::config::Config;
+use cohort_seeder::domain::{PersonRange, ProjectedKeys, UtcMillis};
+use envconfig::Envconfig;
+use serde::Deserialize;
+use serde_json::Value;
+use uuid::Uuid;
+
+/// One blob as ClickHouse would hold the `properties` column, and the keys a run's conditions read.
+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
+/// server-side test could disagree with the fold, and a sample of real properties would carry
+/// customer data while covering none of the hostile shapes.
+const CORPUS: &[Case] = &[
+ // The saving: an object carrying none of the keys is dropped.
+ case(r#"{}"#, &["email"]),
+ case(r#"{"other":1}"#, &["email"]),
+ case(r#"{"plan":"paid"}"#, &["email"]),
+ // Present in any form, including a null value, keeps the row.
+ case(r#"{"email":"[email protected]"}"#, &["email"]),
+ case(r#"{"email":null}"#, &["email"]),
+ case(r#"{"email":""}"#, &["email"]),
+ case(r#"{"plan":"paid","email":"[email protected]"}"#, &["email", "plan"]),
+ case(r#"{"plan":"paid"}"#, &["email", "plan"]),
+ // Key matching is exact: a case difference, a nested occurrence, or a near-miss must not admit.
+ case(r#"{"Email":"[email protected]"}"#, &["email"]),
+ case(r#"{"EMAIL":"[email protected]"}"#, &["email"]),
+ case(r#"{"a":{"email":1}}"#, &["email"]),
+ case(r#"{"emai":1,"emails":2,"email2":3}"#, &["email"]),
+ // Duplicate keys, which ClickHouse keeps in order and `serde_json` collapses to the last.
+ case(r#"{"email":"a","email":"b"}"#, &["email"]),
+ case(r#"{"other":1,"other":2}"#, &["email"]),
+ // Whitespace around a valid object is still an object to both parsers.
+ case(" \t{\"email\":\"[email protected]\"}\n ", &["email"]),
+ case(" \t{\"other\":1}\n ", &["email"]),
+ // Keys that have to survive both the SQL literal escaping and JSON key decoding.
+ case(r#"{"$feature/flag":"variant"}"#, &["$feature/flag"]),
+ case(r#"{"has space":1}"#, &["has space"]),
+ case(r#"{"quote\"key":1}"#, &["quote\"key"]),
+ case(r#"{"back\\slash":1}"#, &["back\\slash"]),
+ case(r#"{"question?":1}"#, &["question?"]),
+ case(r#"{"why?fields":1}"#, &["why?fields"]),
+ case(r#"{"new\nline":1}"#, &["new\nline"]),
+ case(r#"{"tab\tkey":1}"#, &["tab\tkey"]),
+ case(r#"{"":1}"#, &[""]),
+ case(r#"{"é😀":1}"#, &["é😀"]),
+ // A key written as a JSON escape has to match the decoded name a condition reads: ClickHouse
+ // and `serde_json` both decode key escapes, and the globals a condition indexes into hold the
+ // decoded name.
+ case(r#"{"\u0065mail":"[email protected]"}"#, &["email"]),
+ case(r#"{"\ud83d\ude00":1}"#, &["😀"]),
+ case(r#"{"\u0065mail":1}"#, &["\\u0065mail"]),
+ // The single quote is the one escape whose failure would be an injection rather than a wrong
+ // answer. A predicate that broke out of its literal would admit or drop everything.
+ case(r#"{"quote' OR 1 = 1 --":1}"#, &["quote' OR 1 = 1 --"]),
+ case(r#"{"other":1}"#, &["quote' OR 1 = 1 --"]),
+ // Non-objects: all admitted, because the seeder's fold is what decides them.
+ case(r#"[1]"#, &["email"]),
+ case(r#"[{"email":"[email protected]"}]"#, &["email"]),
+ case(r#""a string""#, &["email"]),
+ case(r#"42"#, &["email"]),
+ case(r#"true"#, &["email"]),
+ case(r#"null"#, &["email"]),
+ case(r#""#, &["email"]),
+ case(r#"{not json"#, &["email"]),
+ case(r#"{"email":1,"#, &["email"]),
+ case(r#"{'email':1}"#, &["email"]),
+ // The case the plan's tighter predicate would have dropped: ClickHouse gives up on the whole
+ // document over a number it cannot represent and reports `Null`, while `serde_json` parses it
+ // and the VM reads `email` — so this person is a member the scan must not drop.
+ case(
+ r#"{"email":"[email protected]","big":123456789012345678901234567890}"#,
+ &["email"],
+ ),
+ case(r#"{"email":"[email protected]","huge":1e309}"#, &["email"]),
+ // Many keys, one read: the shape the filter exists for.
+ case(
+ r#"{"k0":0,"k1":1,"k2":2,"k3":3,"k4":4,"k5":5,"k6":6,"k7":7,"k8":8,"k9":9}"#,
+ &["email"],
+ ),
+];
+
+/// Stands in for the `person` table under `EXPLAIN`: every column the scan reads, none of them
+/// constant, so the planner cannot fold a predicate or an aggregate away before it is counted.
+const PERSON_SOURCE: &str = "(SELECT generateUUIDv4() AS id, toInt64(number % 3) AS team_id, toString(number) AS properties, toUInt64(number) AS version, toInt8(number % 2) AS is_deleted, toDateTime(number) AS _timestamp FROM numbers(8))";
+
+#[derive(Row, Deserialize)]
+struct Admitted {
+ index: u32,
+ admitted: bool,
+}
+
+#[derive(Row, Deserialize)]
+struct ExplainLine {
+ explain: String,
+}
+
+#[tokio::test]
+async fn the_key_filter_drops_exactly_the_key_less_object_blobs() {
+ let client = connect();
+ // Grouped by key set because that is what the predicate is rendered from, so one query per
+ // distinct set covers the 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 admitted = admit_all(&client, keys, &blobs).await;
+ for (blob, admitted) in blobs.iter().zip(&admitted) {
+ assert_eq!(
+ *admitted,
+ oracle(blob, keys),
+ "blob {blob:?} against keys {keys:?}"
+ );
+ }
+ }
+}
+
+/// A large object must still be read key by key rather than truncated somewhere.
+#[tokio::test]
+async fn a_large_object_is_still_read_key_by_key() {
+ let client = connect();
+ let mut wide = String::from("{");
+ for index in 0..4_000 {
+ if index > 0 {
+ wide.push(',');
+ }
+ wide.push_str(&format!("\"k{index}\":\"{}\"", "v".repeat(20)));
+ }
+ let without = format!("{wide}}}");
+ let with = format!("{wide},\"email\":\"[email protected]\"}}");
+ assert!(with.len() > 100_000, "the wide blob is meant to be large");
+
+ let admitted = admit_all(&client, &["email"], &[&without, &with]).await;
+ assert_eq!(admitted, vec![false, true]);
+}
+
+/// The rendered scan names `argMax(p.properties, p.version)` three times — once in the select list
+/// and twice in the filter — because a bare `properties` in `HAVING` would bind to the output alias
+/// instead of the column. ClickHouse has to fold those into one aggregate state, or the filter costs
+/// every chunk two extra passes over the widest column in the table.
+#[tokio::test]
+async fn the_repeated_aggregate_is_computed_once() {
+ let client = connect();
+ let keys = ProjectedKeys::new(BTreeSet::from(["email".to_owned()])).unwrap();
+ let spec = PersonScanSpec::new(
+ cohort_core::filters::TeamId(2),
+ UtcMillis::new(1_780_000_000_000),
+ PersonRange::new(Uuid::nil(), None).unwrap(),
+ Some(keys),
+ );
+ let sql = person_scan_sql(&spec);
+ assert_eq!(
+ sql.matches("argMax(p.properties, p.version)").count(),
+ 3,
+ "the rendered text is meant to name the aggregate three times"
+ );
+
+ // The compose stack's ClickHouse carries no PostHog schema, so the scan is re-pointed at an
+ // inline source with the columns it reads. Folding a repeated aggregate is the analyzer's
+ // doing and does not depend on where the rows come from.
+ let explained = sql.replace("FROM person AS ", &format!("FROM {PERSON_SOURCE} AS "));
+ assert_eq!(
+ explained.matches(PERSON_SOURCE).count(),
+ 2,
+ "both references to the person table are meant to be re-pointed"
+ );
+ let plan = client
+ .query(&format!("EXPLAIN actions = 1 {explained}"))
+ .fetch_all::<ExplainLine>()
+ .await
+ .unwrap_or_else(|error| panic!("EXPLAIN failed: {error}\n{explained}"))
+ .into_iter()
+ .map(|line| line.explain)
+ .collect::<Vec<_>>();
+ assert!(plan.len() > 1, "the plan did not decode: {plan:?}");
+
+ // The `Aggregates:` block lists each distinct aggregate once, as a bare
+ // `argMax(<table>.properties, <table>.version)` line with no `Function:`/`Arguments:` prefix.
+ let states = plan
+ .iter()
+ .filter(|line| {
+ let line = line.trim();
+ line.starts_with("argMax(") && line.contains("properties") && line.ends_with(')')
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ states.len(),
+ 1,
+ "the repeated aggregate was not folded into one state: {states:?}\n{}",
+ plan.join("\n")
+ );
+}
+
+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 predicate over `blobs`, in the blobs' own order.
+async fn admit_all(client: &Client, keys: &[&str], blobs: &[&str]) -> Vec<bool> {
+ let sql = format!(
+ "WITH ? AS blobs\nSELECT index, {} AS admitted\nFROM (SELECT arrayJoin(arrayEnumerate(blobs)) AS index, blobs[index] AS blob)\nORDER BY index",
+ predicate_over("blob", keys),
+ );
+ let owned = blobs
+ .iter()
+ .map(|blob| (*blob).to_owned())
+ .collect::<Vec<_>>();
+ let rows = client
+ .query(&sql)
+ .bind(owned)
+ .fetch_all::<Admitted>()
+ .await
+ .unwrap_or_else(|error| panic!("the key-filter 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 promised order has to hold before the results are stripped to booleans.
+ 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.admitted).collect()
+}
+
+/// The predicate exactly as `person_scan_sql` renders it, lifted out of the surrounding scan and
+/// re-pointed at `column`. Extracted from a rendered scan rather than re-assembled, so a change to
+/// the production text cannot slip past this file.
+fn predicate_over(column: &str, keys: &[&str]) -> String {
+ let keys = ProjectedKeys::new(keys.iter().map(|key| (*key).to_owned()).collect())
+ .expect("every corpus case names at least one key");
+ let spec = PersonScanSpec::new(
+ cohort_core::filters::TeamId(2),
+ UtcMillis::new(1_780_000_000_000),
+ PersonRange::new(Uuid::nil(), None).unwrap(),
+ Some(keys),
+ );
+ let sql = person_scan_sql(&spec);
+ let predicate = sql
+ .split_once("\n AND (JSONType")
+ .and_then(|(_, rest)| rest.split_once("\nSETTINGS"))
+ .map(|(predicate, _)| format!("(JSONType{predicate}"))
+ .expect("the rendered scan carries the key filter");
+ predicate.replace("argMax(p.properties, p.version)", column)
+}
+
+/// What the seeder's own fold does with a blob: an object is worth scanning only when it carries a
+/// key, and every other blob is the fold's to decide.
+fn oracle(blob: &str, keys: &[&str]) -> bool {
+ match serde_json::from_str::<Value>(blob) {
+ Ok(Value::Object(map)) => keys.iter().any(|key| map.contains_key(*key)),
+ Ok(_) | Err(_) => true,
+ }
+}
+
+/// The oracle itself, so a mistake in it cannot quietly weaken every assertion above.
+#[test]
+fn the_oracle_admits_every_non_object_and_reads_object_keys_exactly() {
+ assert!(!oracle(r#"{}"#, &["email"]));
+ assert!(!oracle(r#"{"Email":1}"#, &["email"]));
+ assert!(!oracle(r#"{"a":{"email":1}}"#, &["email"]));
+ assert!(oracle(r#"{"email":null}"#, &["email"]));
+ assert!(oracle(r#"{"plan":1}"#, &["email", "plan"]));
+ for admitted in [r#"[1]"#, r#""s""#, r#"42"#, r#"null"#, r#""#, r#"{bad"#] {
+ assert!(oracle(admitted, &["email"]), "{admitted} must be admitted");
+ }
+}