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.

fix(autoresearch): stop labeler queries from reading the whole team (#109088)

posthog[bot]7d341328caed
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
index c3a2068fec42..1b56e5b81fd0 100644
--- a/products/autoresearch/backend/dataset/AGENTS.md
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -11,6 +11,7 @@ Nothing here trains or scores anything. It is the shared vocabulary that `../tra
A training example is a `(person, T0, label)` triple: pick an anchor time `T0` for a person, then `label = 1` if the target event fires in `[T0, T0 + horizon_days)`.
`T0` is a **deterministic hash of `person_id`**, placed at a fixed fraction of the user's `[first_ts, cutoff_ts)` span, so it is stable across runs and spread across the full lookback rather than clustered at the most-recent feasible point — one row per person, sampled once in their history. A `hash % span` remainder would move every time `cutoff_ts` moved with `now()`.
+ For an event-defined population (`performed_event_within_days` with an event, `ever_performed_event`, `ever_performed_target`), `first_ts` is the user's first population event, not their first event of any kind. The other populations still start the span at the first event of any kind.
Three call sites share this module so they cannot drift: the wizard's live estimate (sampled), the trainer (full materialization with fold split), and inference (per-person cutoff = `now()`).
That is why the training-side `labeled_anchors` CTE (inside `build_training_features_sql()`) and `build_inference_anchors_sql()` live here rather than next to their callers.
@@ -47,6 +48,8 @@ The two branches differ only in cutoff and whether labels and folds are attached
- **Validation is advisory, not enforcing.** `autoresearch_train` does not call it. A target that fails on volume will still train — deliberately, so thin local datasets are workable, but it means "the run completed" does not mean "the data was sufficient."
- **Random `T0` is a modeling decision, not an implementation detail.** Spreading anchors across the lookback keeps the model from over-fitting to one moment in calendar time. Changing it to most-recent-feasible would change what every model in the product means.
- **Everything keys on `person_id`.** See `../inference/AGENTS.md` for what goes wrong when a caller keys on `distinct_id` instead — it fails silently.
+- **Never read `person.*` off an events scan here.** It joins the team's whole persons table into the scan, and on a high-volume project the query times out before it starts. Identity and person-property filters go through `_person_rows_sql()`, which reads `raw_persons` pruned to the member ids.
+- **Scan the population's own event where one exists.** `person_id` is not in the events sort key, so a `person_id IN (...)` membership filter does not narrow an any-event scan. A kind sets `member_predicate` so the member scans filter on `event`, which the sort key prunes. An event-property filter keeps the any-event scan, because it can match any event.
## Where the rest of the system meets this package
@@ -62,6 +65,6 @@ The two branches differ only in cutoff and whether labels and folds are attached
- Keep the training-side `labeled_anchors` CTE and `build_inference_anchors_sql()` symmetrical. They should differ in cutoff, labels, and folds — nothing else.
- Every activity scan here excludes the product's own `autoresearch_prediction` event (`_own_events_excluded_clause()`). A live cadence writes one per scored person, so counting it would keep a person eligible forever on nothing but their own predictions. Add the clause to any new events scan.
- New population kinds need the semantic spec in `templates.py`, a compiler function registered in `_POPULATION_KIND_COMPILERS` in `labeling.py` (handling both row mode and anchor mode), and the required-key rules in the `PopulationDefinitionField` validator in `../presentation/views/serializers.py`. `POPULATION_KINDS` is derived from that registry, so a kind cannot exist without a compiler; the write-time validator rejects an unregistered kind at creation. A target-relative kind also has to join `TARGET_RELATIVE_KINDS`, which is still a hand-written list — otherwise `_target_condition_for` resolves no target and the compiler raises at query time.
-- Every population kind and every event-property filter is evaluated **per user at T0** during training (the `HAVING` clause of the labeled CTE) and **as of the cutoff** at inference; only person-property filters apply at the scan. Deciding training membership as of `now()` would admit users on activity after T0, including the outcome window, and excluding "ever performed the target" users with a plain row filter would delete exactly the users whose post-T0 adoption provides the positive labels.
+- Every population kind and every event-property filter is evaluated **per user at T0** during training (the `HAVING` clause of the labeled CTE) and **as of the cutoff** at inference; only person-property filters apply up front, through `raw_persons`. Deciding training membership as of `now()` would admit users on activity after T0, including the outcome window, and excluding "ever performed the target" users with a plain row filter would delete exactly the users whose post-T0 adoption provides the positive labels.
- Fold 0 is the holdout everywhere. If you change `NUM_FOLDS` or the holdout fold, every recorded `holdout_score` in the database becomes incomparable to new ones.
- **If you change the anchor, label, or population contract, update this file to match.**
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index 18952875d42d..3eb5799fcd56 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -66,12 +66,12 @@ TARGET_RELATIVE_KINDS = frozenset({"active_not_performed_target", "ever_performe
# population-agnostic.
IDENTIFIED_USERS_ONLY = True
-# `is_identified` is a column on the persons table, not a person property, so it resolves
-# only while `person` on an events scan reaches the persons table through the lazy join.
-# A team on persons-on-events reads person columns off the event row, where the field does
-# not exist, and HogQL raises `Field not found: is_identified`. Every caller that executes
-# SQL from this module must pass these modifiers so the mode is the one the SQL is built
-# for, whatever mode the team is on.
+# The builders here read identity and person properties from `raw_persons` (see
+# `_person_rows_sql`), never from `person.*` on an events scan, so these modifiers join no
+# persons table into them. They pin how `person_id` resolves, so the anchors and the agent's
+# feature SQL agree on it whatever mode the team is on, and a `person.*` column in feature
+# SQL resolves through the persons table. Every caller that executes SQL from this module
+# must pass them.
LABELER_QUERY_MODIFIERS = HogQLQueryModifiers(
personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED
)
@@ -103,8 +103,8 @@ MATERIALIZE_ROW_LIMIT = 50_000
@dataclass(frozen=True, kw_only=True)
class _CompiledPopulationFilters:
- # Row-level fragments for an events scan whose ``person`` resolves through the lazy join.
- where_parts: list[str] = field(default_factory=list)
+ # Person-property fragments on `raw_persons` columns, decided on each person's latest version.
+ person_parts: list[str] = field(default_factory=list)
# Event-property fragments, kept apart because training decides them per user at T0.
event_parts: list[str] = field(default_factory=list)
values: dict[str, Any] = field(default_factory=dict)
@@ -202,8 +202,8 @@ def _compile_population_filters(properties: list[dict[str, Any]]) -> _CompiledPo
strings and a values dict for parameterized binding.
Property types:
- - "person" → person.properties[<key>] (events table context)
- - "event" → properties[<key>]
+ - "person" → properties[<key>] (raw_persons context, see ``_person_rows_sql``)
+ - "event" → properties[<key>] (events table context)
Operators: exact, is_not, icontains, not_icontains, gt, gte, lt, lte,
is_set, is_not_set.
@@ -233,10 +233,8 @@ def _compile_population_filters(properties: list[dict[str, Any]]) -> _CompiledPo
raise ValueError(f"Population property filter '{key}' is missing a 'type'. Supported: event, person")
if prop_type == "person":
- map_expr = "person.properties"
parts = person_parts
elif prop_type == "event":
- map_expr = "properties"
parts = event_parts
else:
raise ValueError(f"Unsupported population property type '{prop_type}'. Supported: event, person")
@@ -252,7 +250,7 @@ def _compile_population_filters(properties: list[dict[str, Any]]) -> _CompiledPo
values[key_param] = key
compiled = _compile_filter_operator(
- f"{map_expr}[{{{key_param}}}]",
+ f"properties[{{{key_param}}}]",
operator,
prop.get("value"),
key=key,
@@ -262,15 +260,30 @@ def _compile_population_filters(properties: list[dict[str, Any]]) -> _CompiledPo
if compiled.condition is not None:
parts.append(compiled.condition)
- return _CompiledPopulationFilters(where_parts=person_parts, event_parts=event_parts, values=values)
+ return _CompiledPopulationFilters(person_parts=person_parts, event_parts=event_parts, values=values)
-def _build_population_conditions(
- properties: list[dict[str, Any]],
-) -> tuple[list[str], dict[str, Any]]:
- """Row-mode view of ``_compile_population_filters``: every filter applies to the scanned rows."""
- compiled = _compile_population_filters(properties)
- return compiled.where_parts + compiled.event_parts, compiled.values
+def _person_rows_sql(
+ members_sql: str,
+ person_parts: list[str],
+ *,
+ select: str = "id",
+ identified_only: bool = IDENTIFIED_USERS_ONLY,
+) -> str:
+ """
+ One row per live person among ``members_sql``, read from ``raw_persons``.
+
+ The ``id IN`` filter sits inside the version dedupe, so ClickHouse reads only the
+ members' rows through the person sort key. The HogQL ``persons`` table dedupes every
+ person of the team before any filter applies. Each person condition is evaluated on
+ every version and ``argMax`` keeps the latest version's result. ``ifNull`` reads a NULL
+ result (a missing property) as false, as an events-scan WHERE does.
+ """
+ having = ["argMax(is_deleted, version) = 0"]
+ if identified_only:
+ having.append("argMax(is_identified, version) = 1")
+ having.extend(f"argMax(ifNull(({part}), 0), version) = 1" for part in person_parts)
+ return f"SELECT {select} FROM raw_persons WHERE id IN ({members_sql}) GROUP BY id HAVING {' AND '.join(having)}"
# Anchor-mode predicates run inside the labeled_users CTE, where the events scan is aliased
@@ -285,6 +298,11 @@ class _CompiledPopulationKind:
values: dict[str, Any] = field(default_factory=dict)
# Training-only predicates applied per user at T0 in the labeled_users HAVING clause.
anchor_having_parts: list[str] = field(default_factory=list)
+ # Row-mode conditions on `raw_persons` columns, applied by `_person_rows_sql`.
+ person_parts: list[str] = field(default_factory=list)
+ # The row predicate that every member event matches. When set, the member scans read only
+ # these events, which the events sort key prunes. None means membership needs any event.
+ member_predicate: str | None = None
def _members_within(instant: str, days_param: str, *, predicate: str = "", negate: bool = False) -> str:
@@ -344,16 +362,19 @@ def _kind_performed_event_within_days(spec: _PopulationKindSpec) -> _CompiledPop
values: dict[str, Any] = {"popk_days": spec.positive_int("days")}
event_clause, event_values = spec.optional_event_clause()
values.update(event_values)
+ member_predicate = "event = {popk_event}" if event_clause else None
if not spec.anchor_mode:
return _CompiledPopulationKind(
where_parts=[_members_within(spec.now_expr, "popk_days", predicate=event_clause)],
values=values,
+ member_predicate=member_predicate,
)
return _CompiledPopulationKind(
# A cheap superset that bounds the scan; the HAVING decides membership at each user's T0.
where_parts=[_members_within(spec.now_expr, "lookback", predicate=event_clause)] if event_clause else [],
values=values,
anchor_having_parts=[f"{_performed_before_t0(event_clause, days_param='popk_days')} = 1"],
+ member_predicate=member_predicate,
)
@@ -365,10 +386,10 @@ def _kind_person_first_seen_within_days(spec: _PopulationKindSpec) -> _CompiledP
if spec.anchor_mode:
return _CompiledPopulationKind(
values=values,
- anchor_having_parts=[f"min(toInt(toUnixTimestamp(e.person.created_at))) >= {_T0} - {{popk_days}} * 86400"],
+ anchor_having_parts=[f"min(u.person_created_ts) >= {_T0} - {{popk_days}} * 86400"],
)
return _CompiledPopulationKind(
- where_parts=[f"person.created_at >= {spec.now_expr} - toIntervalDay({{popk_days}})"],
+ person_parts=[f"created_at >= {spec.now_expr} - toIntervalDay({{popk_days}})"],
values=values,
)
@@ -404,6 +425,7 @@ def _kind_ever_performed_event(spec: _PopulationKindSpec) -> _CompiledPopulation
where_parts=[_members_within(spec.now_expr, "lookback", predicate=event_clause)],
values=values,
anchor_having_parts=[f"{_performed_before_t0(event_clause)} = 1"] if spec.anchor_mode else [],
+ member_predicate="event = {popk_event}",
)
@@ -412,6 +434,7 @@ def _kind_ever_performed_target(spec: _PopulationKindSpec) -> _CompiledPopulatio
return _CompiledPopulationKind(
where_parts=[_members_within(spec.now_expr, "lookback", predicate=target_clause)],
anchor_having_parts=[f"{_performed_before_t0(target_clause)} = 1"] if spec.anchor_mode else [],
+ member_predicate=f"({spec.target_cond})",
)
@@ -486,6 +509,18 @@ def _build_population_kind_conditions(
)
+def _member_clause(compiled_filters: _CompiledPopulationFilters, compiled_kind: _CompiledPopulationKind) -> str:
+ """
+ ``AND (<member predicate>)`` fragment that narrows a member scan to the population's
+ own event, or '' when membership needs any event.
+
+ An event-property filter can match any event, so it keeps the any-event scan.
+ """
+ if compiled_kind.member_predicate is None or compiled_filters.event_parts:
+ return ""
+ return f" AND ({compiled_kind.member_predicate})"
+
+
def _target_condition_for(
population: dict[str, Any] | None,
*,
@@ -565,10 +600,13 @@ def _build_labeled_users_cte(
Caller appends `SELECT ... FROM labeled_users` to use it.
Population membership is decided per user at T0. Person-property filters and
- the kinds' cheap superset fragments narrow the events scan; event-property
- filters and the semantic kinds are evaluated in the labeled_users HAVING
- against each user's own anchor, so the training population is the same one
- inference selects as of its cutoff.
+ identity come from ``raw_persons``, and the kinds' cheap superset fragments
+ narrow the events scan; event-property filters and the semantic kinds are
+ evaluated in the labeled_users HAVING against each user's own anchor, so the
+ training population is the same one inference selects as of its cutoff.
+
+ A kind with a member predicate (an event-defined population) reads only its
+ own events for the T0 span, and only those plus the target for the labels.
sample_limit caps user_window for fast wizard previews; None = full
materialization (trainer).
@@ -579,14 +617,32 @@ def _build_labeled_users_cte(
target_event=target_event, target_definition=target_definition, team=team
)
compiled_kind = _build_population_kind_conditions(training_population, anchor_mode=True, target_cond=target_cond)
- all_parts = compiled_filters.where_parts + compiled_kind.where_parts
- training_clause = f" AND ({' AND '.join(all_parts)})" if all_parts else ""
- identified_clause = _identified_users_and_clause()
+ member_clause = _member_clause(compiled_filters, compiled_kind)
+ superset_clause = f" AND ({' AND '.join(compiled_kind.where_parts)})" if compiled_kind.where_parts else ""
+ member_scan = (
+ "timestamp >= now() - toIntervalDay({lookback})"
+ f" AND timestamp < now(){_own_events_excluded_clause()}{member_clause}{superset_clause}"
+ )
+ persons_sql = _person_rows_sql(
+ f"SELECT person_id FROM events WHERE {member_scan}",
+ compiled_filters.person_parts,
+ select="id, toInt(toUnixTimestamp(argMax(created_at, version))) AS created_ts",
+ )
+ # With a member predicate, the label scan reads only the target and the population event:
+ # the HAVING below needs no other rows. Without one, membership at T0 can need any event.
+ label_scan_clause = ""
+ if member_clause:
+ target_expr = f"({target_cond})"
+ label_scan_clause = (
+ f" AND {target_expr}"
+ if compiled_kind.member_predicate == target_expr
+ else f" AND ({target_expr} OR ({compiled_kind.member_predicate}))"
+ )
# A bare LIMIT would hand back whatever ClickHouse reads first, which correlates with
# storage order; the sampled base rate is extrapolated to the whole population, so order
# by a uniform hash of the person to make the sample representative and reproducible.
limit_clause = (
- f"\n ORDER BY cityHash64(toString(person_id))\n LIMIT {int(sample_limit)}"
+ f"\n ORDER BY cityHash64(toString(m.person_id))\n LIMIT {int(sample_limit)}"
if sample_limit is not None
else ""
)
@@ -604,22 +660,31 @@ def _build_labeled_users_cte(
# the property, and a user whose every in-horizon row is NULL must label 0, not NULL.
# T0 sits at a fixed fraction (hash / 2^31) of the user's [first_ts, cutoff_ts) span. A
# `hash % span` remainder would change every time cutoff_ts moved with now(), handing the
- # same person a different T0, features, and label on each run.
+ # same person a different T0, features, and label on each run. With a member predicate,
+ # first_ts is the user's first population event, else their first event of any kind.
cte = f"""
WITH user_window AS (
SELECT
- person_id,
- toInt(toUnixTimestamp(min(timestamp))) AS first_ts,
- toInt(toUnixTimestamp(now() - toIntervalDay({{horizon}}))) AS cutoff_ts
- FROM events
- WHERE timestamp >= now() - toIntervalDay({{lookback}})
- AND timestamp < now(){_own_events_excluded_clause()}{training_clause}{identified_clause}
- GROUP BY person_id
- HAVING first_ts < cutoff_ts{limit_clause}
+ m.person_id AS person_id,
+ m.first_ts AS first_ts,
+ m.cutoff_ts AS cutoff_ts,
+ p.created_ts AS person_created_ts
+ FROM (
+ SELECT
+ person_id,
+ toInt(toUnixTimestamp(min(timestamp))) AS first_ts,
+ toInt(toUnixTimestamp(now() - toIntervalDay({{horizon}}))) AS cutoff_ts
+ FROM events
+ WHERE {member_scan}
+ GROUP BY person_id
+ HAVING first_ts < cutoff_ts
+ ) AS m
+ INNER JOIN ({persons_sql}) AS p ON m.person_id = p.id{limit_clause}
),
user_t0 AS (
SELECT
person_id,
+ person_created_ts,
first_ts
+ intDiv((cutoff_ts - first_ts) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)
AS t0_ts
@@ -637,7 +702,7 @@ def _build_labeled_users_cte(
FROM events e
INNER JOIN user_t0 u ON e.person_id = u.person_id
WHERE e.timestamp >= now() - toIntervalDay({{lookback}})
- AND e.timestamp < now(){_own_events_excluded_clause("e.")}
+ AND e.timestamp < now(){_own_events_excluded_clause("e.")}{label_scan_clause}
GROUP BY u.person_id, u.t0_ts{anchor_having}
)
"""
@@ -702,8 +767,9 @@ def build_eligible_count_sql(
) -> tuple[str, dict[str, Any]]:
"""
Build a HogQL query returning the count of users eligible to be labeled by the
- random-T0 labeler — i.e. users in the training_population with at least one event
- before now - horizon_days. Used as the UI headline number so the wizard reports
+ random-T0 labeler — i.e. users in the training_population with at least one member
+ event (the population event, or any event when the population names none) before
+ now - horizon_days. Used as the UI headline number so the wizard reports
the full population size, not the sampled subset.
Returns two columns: ``eligible`` (the v1 headline — restricted to identified
@@ -712,7 +778,7 @@ def build_eligible_count_sql(
mostly-anonymous population and warn that v1 excludes the anonymous remainder.
"""
training_properties = (training_population or {}).get("properties", []) if training_population else []
- train_parts, train_values = _build_population_conditions(training_properties)
+ compiled_filters = _compile_population_filters(training_properties)
# Row mode: the target-relative kinds are evaluated as of now() here, which is an
# approximation of the trainer's per-user-at-T0 semantics — acceptable for an
# advisory headline count.
@@ -720,25 +786,35 @@ def build_eligible_count_sql(
training_population, target_event=target_event, target_definition=target_definition, team=team
)
compiled_kind = _build_population_kind_conditions(training_population, target_cond=target_cond)
- all_parts = train_parts + compiled_kind.where_parts
- training_clause = f" AND ({' AND '.join(all_parts)})" if all_parts else ""
-
- horizon_cond = "timestamp < now() - toIntervalDay({horizon})"
- eligible_cond = f"{horizon_cond} AND person.is_identified" if IDENTIFIED_USERS_ONLY else horizon_cond
+ row_parts = compiled_filters.event_parts + compiled_kind.where_parts
+ row_clause = f" AND ({' AND '.join(row_parts)})" if row_parts else ""
+ member_clause = _member_clause(compiled_filters, compiled_kind)
+
+ # A member event before now - horizon is the trainer's `first_ts < cutoff_ts`.
+ members_sql = (
+ "SELECT person_id FROM events"
+ " WHERE timestamp >= now() - toIntervalDay({lookback})"
+ f" AND timestamp < now() - toIntervalDay({{horizon}}){_own_events_excluded_clause()}{member_clause}{row_clause}"
+ )
+ persons_sql = _person_rows_sql(
+ members_sql,
+ compiled_filters.person_parts + compiled_kind.person_parts,
+ select="id, argMax(is_identified, version) AS is_identified",
+ identified_only=False,
+ )
+ eligible_expr = "countIf(is_identified = 1)" if IDENTIFIED_USERS_ONLY else "count()"
sql = f"""
SELECT
- countDistinctIf(person_id, {eligible_cond}) AS eligible,
- countDistinctIf(person_id, {horizon_cond}) AS eligible_all
- FROM events
- WHERE timestamp >= now() - toIntervalDay({{lookback}})
- AND timestamp < now(){_own_events_excluded_clause()}{training_clause}
+ {eligible_expr} AS eligible,
+ count() AS eligible_all
+ FROM ({persons_sql})
"""
values: dict[str, Any] = {
"horizon": horizon_days,
"lookback": lookback_days,
**target_values,
- **train_values,
+ **compiled_filters.values,
**compiled_kind.values,
}
return sql, values
@@ -760,15 +836,16 @@ def build_inference_anchors_sql(
user's state as of right now." Pass an explicit ``cutoff_ts`` (unix seconds)
to backfill a historical prediction date: features are then computed strictly
before that instant, exactly as live scoring would have on that day. Eligible
- = users in inference_population with at least one event in the lookback_days
- window before the cutoff (so there's signal to score on).
+ = users in inference_population with at least one member event (the population
+ event, or any event when the population names none) in the lookback_days window
+ before the cutoff. One row per person, read from ``raw_persons``.
Substituted as the {anchors} table when running the agent's feature_sql
at inference time. Same SQL the trainer executed against per-user T0;
only the anchors table changes.
"""
inference_properties = (inference_population or {}).get("properties", []) if inference_population else []
- inf_parts, inf_values = _build_population_conditions(inference_properties)
+ compiled_filters = _compile_population_filters(inference_properties)
# now() for live scoring; a bound, backdated instant for a historical backfill.
cutoff_expr = "fromUnixTimestamp({cutoff_ts})" if cutoff_ts is not None else "now()"
@@ -782,22 +859,24 @@ def build_inference_anchors_sql(
compiled_kind = _build_population_kind_conditions(
inference_population, now_expr=cutoff_expr, target_cond=target_cond
)
- all_parts = inf_parts + compiled_kind.where_parts
- inf_clause = f" AND ({' AND '.join(all_parts)})" if all_parts else ""
- identified_clause = _identified_users_and_clause()
-
- sql = f"""
- SELECT DISTINCT
- person_id,
- {cutoff_select} AS cutoff_ts
- FROM events
- WHERE timestamp >= {cutoff_expr} - toIntervalDay({{lookback}})
- AND timestamp < {cutoff_expr}{_own_events_excluded_clause()}{inf_clause}{identified_clause}
- """
+ row_parts = compiled_filters.event_parts + compiled_kind.where_parts
+ row_clause = f" AND ({' AND '.join(row_parts)})" if row_parts else ""
+ member_clause = _member_clause(compiled_filters, compiled_kind)
+
+ members_sql = (
+ "SELECT person_id FROM events"
+ f" WHERE timestamp >= {cutoff_expr} - toIntervalDay({{lookback}})"
+ f" AND timestamp < {cutoff_expr}{_own_events_excluded_clause()}{member_clause}{row_clause}"
+ )
+ sql = _person_rows_sql(
+ members_sql,
+ compiled_filters.person_parts + compiled_kind.person_parts,
+ select=f"id AS person_id, {cutoff_select} AS cutoff_ts",
+ )
values: dict[str, Any] = {
"lookback": lookback_days,
**target_values,
- **inf_values,
+ **compiled_filters.values,
**compiled_kind.values,
}
if cutoff_ts is not None:
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index b664443e74aa..93865c8585d2 100644
--- a/products/autoresearch/backend/dataset/test_labeling.py
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -23,8 +23,8 @@ from products.autoresearch.backend.dataset.labeling import (
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
_build_labeled_users_cte,
- _build_population_conditions,
_build_population_kind_conditions,
+ _compile_population_filters,
_substitute_anchors,
build_eligible_count_sql,
build_inference_anchors_sql,
@@ -122,41 +122,41 @@ class TestPopulationFilterCompilation(SimpleTestCase):
)
def test_uncompilable_filter_raises_instead_of_widening(self, _name: str, properties: list[dict[str, Any]]) -> None:
with self.assertRaises(ValueError):
- _build_population_conditions(properties)
+ _compile_population_filters(properties)
@parameterized.expand(
[
# is_set follows the canonical property compiler: an empty string is a set value.
- ("is_set", {"operator": "is_set"}, "isNotNull(person.properties[{pop_k_0}])", {}),
- ("is_not_set", {"operator": "is_not_set"}, "isNull(person.properties[{pop_k_0}])", {}),
+ ("is_set", {"operator": "is_set"}, "isNotNull(properties[{pop_k_0}])", {}),
+ ("is_not_set", {"operator": "is_not_set"}, "isNull(properties[{pop_k_0}])", {}),
(
"icontains_list_matches_any",
{"operator": "icontains", "value": ["pro", "enterprise"]},
- "(person.properties[{pop_k_0}] ILIKE {pop_0_0} OR person.properties[{pop_k_0}] ILIKE {pop_0_1})",
+ "(properties[{pop_k_0}] ILIKE {pop_0_0} OR properties[{pop_k_0}] ILIKE {pop_0_1})",
{"pop_0_0": "%pro%", "pop_0_1": "%enterprise%"},
),
(
"not_icontains_list_excludes_every",
{"operator": "not_icontains", "value": ["pro", "enterprise"]},
- "(person.properties[{pop_k_0}] NOT ILIKE {pop_0_0} AND person.properties[{pop_k_0}] NOT ILIKE {pop_0_1})",
+ "(properties[{pop_k_0}] NOT ILIKE {pop_0_0} AND properties[{pop_k_0}] NOT ILIKE {pop_0_1})",
{"pop_0_0": "%pro%", "pop_0_1": "%enterprise%"},
),
(
"exact_list_is_an_in_clause",
{"operator": "exact", "value": ["pro", "enterprise"]},
- "person.properties[{pop_k_0}] IN ({pop_0_0}, {pop_0_1})",
+ "properties[{pop_k_0}] IN ({pop_0_0}, {pop_0_1})",
{"pop_0_0": "pro", "pop_0_1": "enterprise"},
),
(
"is_not_list_is_a_not_in_clause",
{"operator": "is_not", "value": ["pro", "enterprise"]},
- "person.properties[{pop_k_0}] NOT IN ({pop_0_0}, {pop_0_1})",
+ "properties[{pop_k_0}] NOT IN ({pop_0_0}, {pop_0_1})",
{"pop_0_0": "pro", "pop_0_1": "enterprise"},
),
(
"string_threshold_is_bound_as_a_number",
{"operator": "gte", "value": "13"},
- "toFloat64OrNull(person.properties[{pop_k_0}]) >= {pop_0}",
+ "toFloat64OrNull(properties[{pop_k_0}]) >= {pop_0}",
{"pop_0": 13.0},
),
]
@@ -164,17 +164,17 @@ class TestPopulationFilterCompilation(SimpleTestCase):
def test_compiles_operator(
self, _name: str, filter_fields: dict[str, Any], expected_part: str, expected_values: dict[str, Any]
) -> None:
- parts, values = _build_population_conditions([{"key": "plan", "type": "person", **filter_fields}])
- self.assertEqual(parts, [expected_part])
- self.assertEqual({k: v for k, v in values.items() if k != "pop_k_0"}, expected_values)
+ compiled = _compile_population_filters([{"key": "plan", "type": "person", **filter_fields}])
+ self.assertEqual(compiled.person_parts, [expected_part])
+ self.assertEqual({k: v for k, v in compiled.values.items() if k != "pop_k_0"}, expected_values)
def test_hostile_key_is_bound_not_interpolated(self) -> None:
# Keys are bound as HogQL values, so a hostile key must never reach the SQL text.
hostile_key = "'; DROP TABLE users; --"
- parts, values = _build_population_conditions([{"key": hostile_key, "type": "person", "operator": "is_set"}])
- self.assertEqual(len(parts), 1)
- self.assertNotIn(hostile_key, parts[0])
- self.assertEqual(values["pop_k_0"], hostile_key)
+ compiled = _compile_population_filters([{"key": hostile_key, "type": "person", "operator": "is_set"}])
+ self.assertEqual(len(compiled.person_parts), 1)
+ self.assertNotIn(hostile_key, compiled.person_parts[0])
+ self.assertEqual(compiled.values["pop_k_0"], hostile_key)
@parameterized.expand(
[
@@ -185,10 +185,8 @@ class TestPopulationFilterCompilation(SimpleTestCase):
]
)
def test_empty_value_list(self, _name: str, operator: str, expected_parts: list[str]) -> None:
- parts, _values = _build_population_conditions(
- [{"key": "plan", "type": "person", "operator": operator, "value": []}]
- )
- self.assertEqual(parts, expected_parts)
+ compiled = _compile_population_filters([{"key": "plan", "type": "person", "operator": operator, "value": []}])
+ self.assertEqual(compiled.person_parts, expected_parts)
class TestPopulationKindCompilation(SimpleTestCase):
@@ -212,7 +210,7 @@ class TestPopulationKindCompilation(SimpleTestCase):
(
"first_seen",
{"kind": "person_first_seen_within_days", "days": 14},
- ["person.created_at >= now() - toIntervalDay({popk_days})"],
+ ["argMax(ifNull((created_at >= now() - toIntervalDay({popk_days})), 0), version) = 1"],
{"popk_days": 14},
),
(
@@ -366,7 +364,7 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):
(
"first_seen_window_ends_at_t0",
{"kind": "person_first_seen_within_days", "days": 14},
- ["HAVING min(toInt(toUnixTimestamp(e.person.created_at))) >= u.t0_ts - {popk_days} * 86400"],
+ ["HAVING min(u.person_created_ts) >= u.t0_ts - {popk_days} * 86400"],
["toIntervalDay({popk_days})"],
),
(
@@ -378,10 +376,10 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):
]
},
[
- "AND (isNotNull(person.properties[{pop_k_1}])) AND person.is_identified",
+ "argMax(is_identified, version) = 1 AND argMax(ifNull((isNotNull(properties[{pop_k_1}])), 0), version) = 1",
f"HAVING max(({_EVENT_TS} < u.t0_ts AND (properties[{{pop_k_0}}] = {{pop_0}}))) = 1",
],
- ["AND (properties[{pop_k_0}] = {pop_0}) AND person.is_identified"],
+ ["argMax(ifNull((properties[{pop_k_0}] = {pop_0})", "person."],
),
(
# Inference ANDs event filters on one row, so training must find one pre-T0 event
@@ -474,14 +472,58 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
{"member": _DAILY_PAGEVIEWS},
1,
),
+ (
+ "person_property",
+ {"properties": [{"key": "tier", "type": "person", "operator": "exact", "value": "pro"}]},
+ {"member": _DAILY_PAGEVIEWS, "other_tier": _DAILY_PAGEVIEWS},
+ 1,
+ None,
+ {"member": {"tier": "pro"}, "other_tier": {"tier": "free"}},
+ ),
+ (
+ "identified_only",
+ {},
+ {"member": _DAILY_PAGEVIEWS, "anonymous": _DAILY_PAGEVIEWS},
+ 1,
+ None,
+ {},
+ {"anonymous"},
+ ),
+ (
+ # T0 falls in [first signup, now - horizon), after every target event, so the label is 0.
+ # A span from the first event of any kind would place most T0s among the targets.
+ "t0_spans_from_the_first_population_event",
+ {"kind": "ever_performed_event", "event": "signup"},
+ {
+ "member": [
+ *_DAILY_PAGEVIEWS,
+ *[("feature_used", days_ago) for days_ago in range(100, 20, -1)],
+ *[("signup", days_ago) for days_ago in range(20, 0, -1)],
+ ]
+ },
+ 1,
+ 0,
+ ),
]
)
def test_anchored_population_executes_with_expected_membership(
- self, _name: str, training_population: dict[str, Any], users: dict[str, list[tuple[str, int]]], expected: int
+ self,
+ _name: str,
+ training_population: dict[str, Any],
+ users: dict[str, list[tuple[str, int]]],
+ expected: int,
+ expected_positives: int | None = None,
+ person_properties: dict[str, dict[str, Any]] | None = None,
+ anonymous: set[str] | None = None,
) -> None:
now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())
for distinct_id, events in users.items():
- _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], is_identified=True)
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=[distinct_id],
+ is_identified=distinct_id not in (anonymous or set()),
+ properties=(person_properties or {}).get(distinct_id, {}),
+ )
for event, days_ago in events:
_create_event(
team=self.team,
@@ -505,3 +547,43 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
)
assert int(rows[0][0]) == expected
+ if expected_positives is not None:
+ assert int(rows[0][1]) == expected_positives
+
+ @parameterized.expand(
+ [
+ ("any_event_population", None),
+ ("population_event_member_scan", {"kind": "ever_performed_event", "event": "$pageview"}),
+ ]
+ )
+ def test_row_mode_counts_read_identity_and_person_filters_from_raw_persons(
+ self, _name: str, kind: dict[str, Any] | None
+ ) -> None:
+ now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())
+ for distinct_id, tier, identified in [("pro", "pro", True), ("free", "free", True), ("anon_pro", "pro", False)]:
+ _create_person(
+ team_id=self.team.pk, distinct_ids=[distinct_id], is_identified=identified, properties={"tier": tier}
+ )
+ for _event, days_ago in _DAILY_PAGEVIEWS[-30:]:
+ _create_event(
+ team=self.team, event="$pageview", distinct_id=distinct_id, timestamp=now - timedelta(days=days_ago)
+ )
+ flush_persons_and_events()
+ population = {
+ **(kind or {}),
+ "properties": [{"key": "tier", "type": "person", "operator": "exact", "value": "pro"}],
+ }
+
+ def run(sql: str, values: dict[str, Any]) -> list[Any]:
+ return run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )[0]
+
+ eligible_sql, eligible_values = build_eligible_count_sql(
+ horizon_days=7, lookback_days=90, training_population=population
+ )
+ anchors_sql, anchors_values = build_inference_anchors_sql(lookback_days=30, inference_population=population)
+ assert [int(v) for v in run(eligible_sql, eligible_values)] == [1, 2]
+ assert int(run(f"SELECT count() FROM ({anchors_sql.strip()})", anchors_values)[0]) == 1
diff --git a/products/autoresearch/backend/dataset/test_templates.py b/products/autoresearch/backend/dataset/test_templates.py
index f0f8f7857ee3..7d22db695d28 100644
--- a/products/autoresearch/backend/dataset/test_templates.py
+++ b/products/autoresearch/backend/dataset/test_templates.py
@@ -76,7 +76,7 @@ class TestTemplateSpecsCompile(SimpleTestCase):
for population in (t.training_population_spec, t.inference_population_spec):
row = _build_population_kind_conditions(population, target_cond="event = {target}")
anchor = _build_population_kind_conditions(population, anchor_mode=True, target_cond="event = {target}")
- self.assertTrue(row.where_parts)
+ self.assertTrue(row.where_parts or row.person_parts)
self.assertTrue(anchor.anchor_having_parts)
diff --git a/products/autoresearch/backend/dataset/test_validation.py b/products/autoresearch/backend/dataset/test_validation.py
index 6fc12b667173..a2a5ebcca70c 100644
--- a/products/autoresearch/backend/dataset/test_validation.py
+++ b/products/autoresearch/backend/dataset/test_validation.py
@@ -5,6 +5,8 @@ from parameterized import parameterized
from posthog.hogql.errors import QueryError
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
+
from products.autoresearch.backend.dataset.labeling import LABELER_QUERY_MODIFIERS, PREDICTION_EVENT_NAME
from products.autoresearch.backend.dataset.validation import (
ValidationResult,
@@ -104,6 +106,12 @@ class TestValidationWarnings(BaseTest):
"Validation could not run",
),
("query_error_reaches_the_caller", QueryError("Field not found: nope"), "Field not found: nope"),
+ ("timeout_asks_to_narrow_the_definition", ClickHouseQueryTimeOut(), "Narrow the population"),
+ (
+ "memory_limit_asks_to_narrow_the_definition",
+ ClickHouseQueryMemoryLimitExceeded(),
+ "Narrow the population",
+ ),
]
)
def test_error_in_query_returns_error_result(self, _name: str, exc: Exception, expected: str) -> None:
diff --git a/products/autoresearch/backend/dataset/validation.py b/products/autoresearch/backend/dataset/validation.py
index 2371e854e7b3..1f108d81988e 100644
--- a/products/autoresearch/backend/dataset/validation.py
+++ b/products/autoresearch/backend/dataset/validation.py
@@ -12,6 +12,12 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.dataclasses import frozen
from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import (
+ ClickHouseClusterMemoryLimitExceeded,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -67,12 +73,24 @@ class ValidationWarningCode(StrEnum):
_GENERIC_ERROR = "Validation could not run. Try again, and contact support if it keeps failing."
+_TOO_EXPENSIVE_ERROR = (
+ "Validation ran out of time or memory on this project's data. "
+ "Narrow the population, for example to people who performed a specific event, or shorten the training lookback."
+)
+_TOO_EXPENSIVE_ERRORS = (
+ ClickHouseQueryTimeOut,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+)
def _exposed_error(exc: Exception) -> str:
# Exposed errors describe the caller's own definition, so anything else is our infrastructure and stays in the log.
if isinstance(exc, ExposedHogQLError | ExposedCHQueryError):
return str(exc)
+ # A definition that reads too much data is one the caller can narrow. Cluster memory pressure is transient.
+ if isinstance(exc, _TOO_EXPENSIVE_ERRORS) and not isinstance(exc, ClickHouseClusterMemoryLimitExceeded):
+ return _TOO_EXPENSIVE_ERROR
return _GENERIC_ERROR
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 5ea837e7e227..83d2c3978e1e 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -14,7 +14,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
- `fit_champion_model()` — **train run**, called once at training completion. Materializes the _labeled_ training population, runs the bundle's `train.py`, runs `predict.py` once against the holdout features as a smoke test, and only then persists the fitted `model.pkl` next to the bundle. A bundle whose two scripts disagree fails here, not on the first cadence.
- `score_via_sandbox()` — **predict run**, called every cadence. Loads the persisted `model.pkl`, materializes _only_ the inference population (cutoff at the start of the prediction date, no labels, no holdout, no fold), runs `predict.py`, and hands scores to the emitter. A missing `model.pkl` fails the run.
- Both entry points validate the bundle's `features.sql` with `validate_feature_sql()` (plus no trailing `LIMIT`/`OFFSET`/`SETTINGS`) before any query runs, and run every HogQL query as the pipeline's creator (`_resolve_acting_user()`, or the explicit `user` a management command passes), with `CALCULATE_BLOCKING_ALWAYS` so a cadence never reuses a cached population, and with `LABELER_QUERY_MODIFIERS`, because the anchor SQL reads `person.is_identified` and only resolves under that persons-on-events mode.
+ Both entry points validate the bundle's `features.sql` with `validate_feature_sql()` (plus no trailing `LIMIT`/`OFFSET`/`SETTINGS`) before any query runs, and run every HogQL query as the pipeline's creator (`_resolve_acting_user()`, or the explicit `user` a management command passes), with `CALCULATE_BLOCKING_ALWAYS` so a cadence never reuses a cached population, and with `LABELER_QUERY_MODIFIERS`, so `person_id` resolves the same way in the anchors and the feature SQL, and a `person.*` column in feature SQL resolves through the persons table. The anchor SQL itself reads identity from `raw_persons`, not from `person.*`.
The train run persists `feature_columns.json` next to `model.pkl`; every predict run sends exactly those columns, in that order, filling an absent or null one with zeros, so the fitted model never sees a column set that depends on today's population. A champion fitted before the file existed falls back to deriving the columns from the scoring rows. A fitted column that holds a present non-numeric value fails the run, because the persisted list bypasses `_numeric_feature_cols()` and zero-filling schema drift would emit a plausible wrong prediction.
`materialize_training_data()` writes feature and label parquet files into the sandbox; `MaterializedData` carries the paths and row counts back. Materialized rows must key exactly one person each (`validate_unique_distinct_ids()`), and a training row whose label failed to join fails the run. Feature SQL that returns two columns of the same name fails the run, because `HogQLResult.as_dicts()` keeps only the last value of a repeated name.
Every upload goes through `_write_file()`, which fails the run on a non-zero result: the providers report a failed write through the exit code rather than an exception, and a discarded result would let a script run against a missing input. The train run's smoke test loads the model bytes read back from the sandbox, written to `_SMOKE_MODEL_PKL`, so the bytes the caller persists are the bytes `predict.py` proved it can load.
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index 263a1ae82b86..8fa0157a0820 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -48,13 +48,10 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.autoresearch.backend.dataset.labeling import (
+ IDENTIFIED_USERS_ONLY,
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
- _build_population_conditions,
- _build_population_kind_conditions,
- _identified_users_and_clause,
- _own_events_excluded_clause,
- _target_condition_for,
+ build_inference_anchors_sql,
build_inference_features_sql,
build_training_features_sql,
)
@@ -473,7 +470,7 @@ def _query(*, team: Team, sql: str, values: dict[str, Any], user: User | None, w
HogQL caps a bare SELECT at 100 rows without an error, so every query here carries an
explicit bound, and a result that fills it is treated as truncated: completing would
advance the cadence past the people beyond the cap. The persons-on-events modifiers
- are what make ``person.is_identified`` resolve, and the always-calculate mode stops a
+ keep ``person_id`` resolving the way the labeler's queries do, and the always-calculate mode stops a
cadence reusing a cached population at a stale cutoff.
"""
bounded_sql = sql.rstrip().rstrip(";") + f"\nLIMIT {_MATERIALIZE_ROW_LIMIT}"
@@ -585,34 +582,21 @@ def _population_query(
team: Team | None = None,
) -> _PopulationQuery | None:
"""
- A ``SELECT DISTINCT person_id`` for the people in the inference population, restricted
- to identified users under the v1 scope. None only when nothing restricts the population.
+ A ``SELECT person_id`` for the people in the inference population, one row each, from the
+ scorer's own anchor query, so it is restricted to identified users under the v1 scope. None only when nothing restricts the population.
A configured filter that cannot be compiled raises, because widening to everyone is
the failure being prevented.
"""
- properties = (population or {}).get("properties", [])
- parts, values = _build_population_conditions(properties)
- target_cond, target_values = _target_condition_for(
- population, target_event=target_event, target_definition=target_definition, team=team
- )
- compiled_kind = _build_population_kind_conditions(population, target_cond=target_cond)
- parts.extend(compiled_kind.where_parts)
- values.update(target_values)
- values.update(compiled_kind.values)
- identified_clause = _identified_users_and_clause()
-
- if not parts and not identified_clause:
+ if not IDENTIFIED_USERS_ONLY and not (population or {}).get("properties") and not (population or {}).get("kind"):
return None
-
- values["lookback"] = lookback_days
- # The upper bound keeps a future-dated or imported event from making someone eligible today.
- where_clause = (
- f"timestamp >= now() - toIntervalDay({{lookback}}) AND timestamp < now(){_own_events_excluded_clause()}"
+ anchors_sql, values = build_inference_anchors_sql(
+ lookback_days=lookback_days,
+ inference_population=population,
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
)
- if parts:
- where_clause += " AND " + " AND ".join(parts)
- where_clause += identified_clause
- return _PopulationQuery(sql=f"SELECT DISTINCT person_id FROM events WHERE {where_clause}", values=values)
+ return _PopulationQuery(sql=f"SELECT person_id FROM ({anchors_sql.strip()})", values=values)
def _count_population(*, team: Team, population: _PopulationQuery, user: User) -> int:
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index 4f352ee57333..5932eb2e78a8 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -495,12 +495,12 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
assert {r["distinct_id"] for r in rows} == {"user-1", "user-3"}
sql, values = self._sent(mock_run)
- assert "f.distinct_id IN (SELECT DISTINCT person_id FROM events WHERE" in sql
- assert "person.properties[{pop_k_0}] = {pop_0}" in sql
+ assert "f.distinct_id IN (SELECT person_id FROM (SELECT id AS person_id" in sql
+ assert "argMax(ifNull((properties[{pop_k_0}] = {pop_0}), 0), version) = 1" in sql
assert values["pop_0"] == "pro"
assert sql.rstrip().endswith(f"LIMIT {_MATERIALIZE_ROW_LIMIT}")
count_query = mock_run.call_args_list[1].kwargs["query"]
- assert count_query.query.startswith("SELECT count() FROM (SELECT DISTINCT person_id FROM events WHERE")
+ assert count_query.query.startswith("SELECT count() FROM (SELECT person_id FROM (SELECT id AS person_id")
assert count_query.values["pop_0"] == "pro"
assert all(call.kwargs["user"] == self.user for call in mock_run.call_args_list)
@@ -514,7 +514,7 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
_fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
sql, values = self._sent(mock_run)
- assert "person.is_identified" in sql
+ assert "argMax(is_identified, version) = 1" in sql
assert f"event != '{PREDICTION_EVENT_NAME}'" in sql
assert "timestamp < now()" in sql
assert values["lookback"] == 30