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.

feat(autoresearch): add the query helper and the labeler (4/22) (#88792)

Andrew Maguire46f50375992f
diff --git a/products/autoresearch/AGENTS.md b/products/autoresearch/AGENTS.md
index 88fd2f6c6ff6..e8557476d231 100644
--- a/products/autoresearch/AGENTS.md
+++ b/products/autoresearch/AGENTS.md
@@ -7,7 +7,7 @@ An agent then searches for the best model for that question, and once it finds o
The framing is Karpathy's `autoresearch` prompt pattern: an agent edits one thing, runs a fixed eval, keeps the change if a single metric improved, reverts otherwise, and loops until a stop rule fires.
Here the "one thing" is a feature set plus a model spec, the fixed eval is holdout AUC on a labeled training population, and the loop runs inside a Tasks sandbox.
-This directory currently holds the data model and the access gate only.
+This directory holds the data model, the access gate, and the backend packages that have landed so far; each package has its own `AGENTS.md`.
The training loop, inference, evaluation, the API, the MCP tools, and the frontend land in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).
## Data model in one pass
@@ -45,6 +45,7 @@ These are the ones that have actually broken things.
- **Everything is keyed on `person_id`, one row per person.**
Agent-authored `feature_sql` must be a read-only `SELECT` keyed on `person_id`, and the label and population queries key on it too.
+ The feature SQL exposes that key under the column name `distinct_id` (`a.person_id AS distinct_id`), which is what the training join and the materialized parquet read; the name is historical, the value is always the person id.
A mismatch here does not raise, it silently produces all-zero labels and a degenerate model.
**A uniform score distribution is an identifier mismatch until proven otherwise, not a bad model.**
- **The agent proposes, the backend disposes.**
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
new file mode 100644
index 000000000000..43633fad3de1
--- /dev/null
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -0,0 +1,68 @@
+# Dataset
+
+What the prediction problem actually _is_: who is in the population, what counts as a positive example, and whether the question is answerable at all.
+
+This package landed ahead of its callers. `../training/`, `../inference/`, and `../presentation/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
+
+Nothing here trains or scores anything. It is the shared vocabulary that `../training/` and `../inference/` both compile against — which is the whole point. If the trainer and the scorer disagreed about what a row means, the resulting model would be quietly wrong rather than loudly broken.
+
+## What lives here
+
+- `labeling.py`
+ The single source of truth for "what does a training example look like?", and the most load-bearing module in the product.
+
+ 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()`.
+
+ 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.
+
+ Also here: `_compile_population_filters()` (property filters → HogQL; a cohort filter, an unknown operator, or a filter without a `type` raises rather than being skipped), `_build_population_kind_conditions()` (semantic population kinds → HogQL, see below), `build_target_condition()` (event or action target → predicate), `NUM_FOLDS = 5` with fold 0 as holdout, and `IDENTIFIED_USERS_ONLY`.
+
+- `validation.py`
+ Pre-flight viability. `validate_pipeline_definition()` answers "is there enough here to learn anything?" before a run is launched — `MIN_TRAINING_ROWS` (100), `MIN_POSITIVE_EXAMPLES` (20), `MIN_IDENTIFIED_FRACTION` (0.5).
+ Returns a `ValidationResult` carrying `ValidationWarning`s rather than raising, because the API surfaces them as advice.
+- `templates.py`
+ Built-in starting points. A template resolves to the same pipeline config shape as a fully custom pipeline, so creation and validation behave identically either way — there is no separate template code path downstream.
+ Population specs use a semantic format (`performed_event_within_days`, `person_first_seen_within_days`, `active_not_performed_target`, `ever_performed_event`, `ever_performed_target`) that is compiled to HogQL by `labeling.py`. The target-relative kinds compile against the pipeline's target predicate, so an action target is matched by its matcher and not by its display name.
+ `resolve_activity_event()` picks the team's real activity event, preferring `$pageview` → `$screen` → `$autocapture`, because "active user" means different things on web and mobile.
+
+## Mental model
+
+A pipeline definition is declarative. This package is what turns it into SQL.
+
+```text
+pipeline (target, population, horizon, lookback)
+ │
+ ├─ build_training_features_sql → labeled_anchors CTE: one T0 per person, hashed,
+ │ └─ + labels + fold spread over lookback — the trainer's labeled population
+ │
+ └─ build_inference_anchors_sql → cutoff = now(), no labels, no folds
+ └─ the scorer's population
+```
+
+The two branches differ only in cutoff and whether labels and folds are attached. Everything else — population filters, identified-user restriction, target predicate — is shared code, deliberately.
+
+## Things that bite
+
+- **`IDENTIFIED_USERS_ONLY` is on.** Autoresearch trains on identified users only, so raw event counts badly overstate available training data on anonymous-heavy datasets. A target with thousands of events can yield a few dozen usable rows.
+- **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.
+
+## Where the rest of the system meets this package
+
+- **Trainer** — `../training/` materializes the labeled population from `build_training_features_sql()`.
+- **Scorer** — `../inference/` materializes the unlabeled population from `build_inference_features_sql()`.
+- **API** — `../presentation/views/views.py` calls `validate_pipeline_definition()` for the pre-create check and `resolve_template()` for template-backed creation; `resolve_target()` lives in `../presentation/views/serializers.py` and pairs with `build_target_condition()`.
+- **Command** — `autoresearch_validate` is the headless entry to `validation.py`.
+- **Agent-authored SQL** — the agent's `feature_sql` is spliced against these anchors via `_substitute_anchors()`. The `{anchors}` placeholder is part of the agent's contract, so it is documented in the brief in `../training/runner.py`. Substitution is quote-aware: comments are stripped, a `{anchors}` inside a string literal is kept as a value, and a trailing `;` is dropped so the SQL can be nested.
+
+## When editing this flow
+
+- **Any change to what a row means goes here and only here.** If you add a cutoff rule, a population kind, or a label variant next to a caller instead, the trainer and scorer will drift and the failure will be silent.
+- Keep the training-side `labeled_anchors` CTE and `build_inference_anchors_sql()` symmetrical. They should differ in cutoff, labels, and folds — nothing else.
+- New population kinds need the semantic spec in `templates.py`, the compiler branch in `_build_population_kind_conditions()` in `labeling.py` (both row mode and anchor mode), and the required-key rules in the `PopulationDefinitionField` validator in `../presentation/views/serializers.py`. `POPULATION_KINDS` in `labeling.py` is the shared registry; a kind missing its compiler branch is rejected at creation and 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.
+- 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/CLAUDE.md b/products/autoresearch/backend/dataset/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/autoresearch/backend/dataset/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/autoresearch/backend/dataset/__init__.py b/products/autoresearch/backend/dataset/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
new file mode 100644
index 000000000000..a5645eee79dd
--- /dev/null
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -0,0 +1,858 @@
+"""
+Labeling: build (user, T0, label) triples for horizon-based prediction.
+
+Single source of truth for "what does a training example look like?" Used by
+the wizard's live estimate (sampled), the trainer (full materialization with
+fold split), and inference (per-user cutoff = now). The three call sites share
+this module so they cannot drift apart — the wizard previews the same labels
+the trainer will actually see, and inference scores against the same cutoff
+contract the feature SQL was trained against.
+
+Strategy: random T0 per user (deterministic hash of person_id), one row per
+user. Each user is sampled at a single point in their history; label = whether
+the target event fires in [T0, T0 + horizon_days). Random T0 (rather than
+most-recent-feasible) keeps T0s spread across the full lookback so the model
+generalises across time, not just the trailing horizon window.
+
+Per-user T0 cascades through the rest of the ML pipeline:
+- Feature SQL must read events with `timestamp < cutoff_ts` per user, where
+ cutoff_ts comes from a joined anchors table (the labeled_anchors CTE at
+ training time, build_inference_anchors_sql at scoring time).
+- Holdout split is by user (fold = hash(person_id) % 5) so the same person
+ never appears in both train and holdout.
+- Inference re-uses the same feature SQL with anchors = (person_id, now()).
+
+Integer handling notes:
+- toUnixTimestamp returns UInt32; we cast to Int64 via toInt so subtractions
+ and modulo work in signed space (HogQL exposes toInt → Int64; toUInt* is
+ unsupported).
+- cityHash64 returns UInt64. Casting directly to Int64 can flip sign when the
+ high bit is set, which would place T0 before first_ts. Truncating to the
+ lower 31 bits via bitAnd guarantees a non-negative hash without harming
+ uniformity, and the position arithmetic stays inside Int64.
+"""
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+from posthog.hogql.property import action_to_expr
+
+from products.actions.backend.models.action import Action
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+# Number of folds for hash-based train/holdout split. fold == 0 → holdout (20%).
+NUM_FOLDS = 5
+
+# Semantic population kinds produced by templates.py. Every kind listed here must have a
+# compiler branch in _build_population_kind_conditions below — the write-time validator in
+# presentation/views/serializers.py imports this set, so an uncompilable kind is rejected at creation.
+POPULATION_KINDS = frozenset(
+ {
+ "performed_event_within_days",
+ "person_first_seen_within_days",
+ "active_not_performed_target",
+ "ever_performed_event",
+ "ever_performed_target",
+ }
+)
+
+# Kinds whose membership is defined by the pipeline's own target rather than by a named event.
+TARGET_RELATIVE_KINDS = frozenset({"active_not_performed_target", "ever_performed_target"})
+
+# v1 scope: autoresearch models identified users only. Identified persons carry a
+# stable real distinct_id, so scoring-time identity resolution always succeeds and the
+# prediction event + output person property land on the right person — no phantom,
+# person-less, or v5↔v7 edge cases. Anonymous / pre-signup populations (e.g.
+# anonymous → signup) are deferred to v2. This is a hard limit baked into every
+# population query; flip to False to relax — the rest of the pipeline is
+# population-agnostic.
+IDENTIFIED_USERS_ONLY = True
+
+
+def _identified_users_and_clause() -> str:
+ """`AND person.is_identified` fragment for an events-table WHERE, or '' when the
+ v1 identified-only scope is disabled. The events table must be unaliased at the
+ call site (or aliased so that ``person`` still resolves via the lazy join)."""
+ return " AND person.is_identified" if IDENTIFIED_USERS_ONLY else ""
+
+
+@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)
+ # 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)
+
+
+def _numeric_threshold(value: Any) -> float | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value)
+ except ValueError:
+ return None
+ return None
+
+
+def _compile_population_filters(properties: list[dict[str, Any]]) -> _CompiledPopulationFilters:
+ """
+ Translate a list of PostHog property filter dicts into HogQL condition
+ strings and a values dict for parameterized binding.
+
+ Property types:
+ - "person" → person.properties[<key>] (events table context)
+ - "event" → properties[<key>]
+
+ Operators: exact, is_not, icontains, not_icontains, gt, gte, lt, lte,
+ is_set, is_not_set. ``is_set`` means not null, as in the canonical
+ property compiler, so an empty string is a set value.
+
+ The property key is bound as a HogQL value (a parameterized subscript,
+ ``properties[{param}]``) rather than interpolated into the query text, so any
+ key — including PostHog system properties like ``$browser`` — is safe without
+ an allowlist. A filter that cannot be compiled (a cohort filter, an unknown
+ operator, a missing key or type, a non-numeric threshold) raises ValueError:
+ skipping it would silently widen the population, and inference writes person
+ properties for everyone it scores. ``type`` has no default because the
+ canonical compiler defaults it to ``event`` while this compiler's callers
+ mostly mean ``person``; a filter that says neither is ambiguous.
+ """
+ person_parts: list[str] = []
+ event_parts: list[str] = []
+ values: dict[str, Any] = {}
+
+ for i, prop in enumerate(properties):
+ key = prop.get("key")
+ prop_type = prop.get("type")
+ operator = prop.get("operator", "exact")
+ value = prop.get("value")
+
+ if not key:
+ raise ValueError("Population property filter is missing a 'key'")
+ if not prop_type:
+ 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")
+
+ # Bind the key as a value (parameterized subscript) — never interpolate it into SQL text.
+ key_param = f"pop_k_{i}"
+ values[key_param] = str(key)
+ field_expr = f"{map_expr}[{{{key_param}}}]"
+
+ param = f"pop_{i}"
+
+ if operator == "is_set":
+ parts.append(f"isNotNull({field_expr})")
+ elif operator == "is_not_set":
+ parts.append(f"isNull({field_expr})")
+ elif operator in ("exact", "is_not") and isinstance(value, list):
+ if not value:
+ # `IN ()` is not valid HogQL. An empty allowlist matches nobody and an
+ # empty denylist excludes nobody.
+ if operator == "exact":
+ parts.append("1 = 0")
+ continue
+ for j, v in enumerate(value):
+ values[f"pop_{i}_{j}"] = v
+ in_refs = ", ".join(f"{{pop_{i}_{j}}}" for j in range(len(value)))
+ membership = "IN" if operator == "exact" else "NOT IN"
+ parts.append(f"{field_expr} {membership} ({in_refs})")
+ elif operator == "exact":
+ values[param] = value
+ parts.append(f"{field_expr} = {{{param}}}")
+ elif operator == "is_not":
+ values[param] = value
+ parts.append(f"{field_expr} != {{{param}}}")
+ elif operator in ("icontains", "not_icontains"):
+ # A list matches any of its values, or none of them for the negative operator.
+ patterns = value if isinstance(value, list) else [value]
+ if not patterns:
+ if operator == "icontains":
+ parts.append("1 = 0")
+ continue
+ for j, v in enumerate(patterns):
+ values[f"pop_{i}_{j}"] = f"%{v}%"
+ like = "ILIKE" if operator == "icontains" else "NOT ILIKE"
+ joiner = " OR " if operator == "icontains" else " AND "
+ clauses = joiner.join(f"{field_expr} {like} {{pop_{i}_{j}}}" for j in range(len(patterns)))
+ parts.append(f"({clauses})" if len(patterns) > 1 else clauses)
+ elif operator in ("gt", "gte", "lt", "lte"):
+ op_sql = {"gt": ">", "gte": ">=", "lt": "<", "lte": "<="}[operator]
+ # The property side is cast to Float64, so the bound must be numeric too or
+ # ClickHouse rejects the comparison. Filter payloads often carry it as a string.
+ threshold = _numeric_threshold(value)
+ if threshold is None:
+ raise ValueError(f"Population property filter '{key}' needs a numeric value for '{operator}'")
+ values[param] = threshold
+ parts.append(f"toFloat64OrNull({field_expr}) {op_sql} {{{param}}}")
+ else:
+ raise ValueError(f"Unsupported population property operator '{operator}'")
+
+ return _CompiledPopulationFilters(where_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
+
+
+# Anchor-mode predicates run inside the labeled_users CTE, where the events scan is aliased
+# ``e`` and each user's T0 comes from the joined ``u`` row.
+_EVENT_TS = "toInt(toUnixTimestamp(e.timestamp))"
+_T0 = "u.t0_ts"
+
+
+@dataclass(frozen=True, kw_only=True)
+class _CompiledPopulationKind:
+ where_parts: list[str] = field(default_factory=list)
+ 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)
+
+
+def _members_within(instant: str, days_param: str, *, predicate: str = "", negate: bool = False) -> str:
+ """Row filter: users with an event matching ``predicate`` in the ``days_param``-day window ending at ``instant``."""
+ membership = "NOT IN" if negate else "IN"
+ return (
+ f"person_id {membership} (SELECT DISTINCT person_id FROM events"
+ f" WHERE timestamp >= {instant} - toIntervalDay({{{days_param}}})"
+ f" AND timestamp < {instant}{predicate})"
+ )
+
+
+def _performed_before_t0(predicate: str, *, days_param: str | None = None) -> str:
+ """Per-user aggregate: 1 when an event matching ``predicate`` precedes T0, within ``days_param`` days of it if given."""
+ window = f"{_EVENT_TS} < {_T0}"
+ if days_param is not None:
+ window = f"{_EVENT_TS} >= {_T0} - {{{days_param}}} * 86400 AND {window}"
+ return f"max(({window}{predicate}))"
+
+
+def _build_population_kind_conditions(
+ population: dict[str, Any] | None,
+ *,
+ now_expr: str = "now()",
+ anchor_mode: bool = False,
+ target_cond: str | None = None,
+) -> _CompiledPopulationKind:
+ """
+ Compile a semantic population spec (``{"kind": ..., ...}``, produced by
+ templates.py) into HogQL fragments for an events scan.
+
+ Membership subqueries are bounded to the caller's lookback window, so
+ "ever performed" and "has not performed" mean "within the lookback window" —
+ the scan cost stays proportional to the data the query already reads. The
+ emitted fragments reference the ``{lookback}`` bound value, which every
+ population-consuming builder in this module binds.
+
+ ``now_expr`` is the anchor instant — ``now()`` for live queries, or a bound
+ backfill cutoff expression for historical scoring. Row-mode windows are
+ computed relative to it.
+
+ ``anchor_mode=True`` (training) decides membership per user at that user's
+ own T0 instead of at ``now_expr``: the tests move from ``where_parts`` into
+ ``anchor_having_parts``, which ``_build_labeled_users_cte`` applies against
+ each user's anchor, exactly as inference decides them as of its cutoff.
+ Deciding training membership as of now() would admit users on activity after
+ T0 (including the outcome window), and a row-level "has not performed the
+ target" filter would delete exactly the users whose post-T0 adoption provides
+ the positive labels. Where a cheap superset exists it stays in ``where_parts``
+ to bound the scan.
+
+ ``target_cond`` is the predicate from ``build_target_condition``. The
+ target-relative kinds require it, so an action target is matched by its
+ compiled matcher rather than by its display name.
+
+ Raises ValueError on an unknown kind or a spec missing a required key — a
+ population that cannot be compiled must fail loudly rather than silently
+ widening to "all users".
+ """
+ spec = population or {}
+ kind = spec.get("kind")
+ if kind is None:
+ return _CompiledPopulationKind()
+ if kind not in POPULATION_KINDS:
+ raise ValueError(f"Unknown population kind '{kind}'. Supported: {', '.join(sorted(POPULATION_KINDS))}")
+
+ def _positive_int(key: str) -> int:
+ raw = spec.get(key)
+ if not isinstance(raw, int) or isinstance(raw, bool) or raw <= 0:
+ raise ValueError(f"Population kind '{kind}' requires a positive integer '{key}'")
+ return raw
+
+ def _event_clause() -> str:
+ raw = spec.get("event")
+ if not raw or not isinstance(raw, str):
+ raise ValueError(f"Population kind '{kind}' requires an 'event'")
+ values["popk_event"] = raw
+ return " AND event = {popk_event}"
+
+ def _target_clause() -> str:
+ if target_cond is None:
+ raise ValueError(f"Population kind '{kind}' requires the pipeline's target predicate")
+ return f" AND ({target_cond})"
+
+ parts: list[str] = []
+ values: dict[str, Any] = {}
+ having: list[str] = []
+
+ if kind == "performed_event_within_days":
+ values["popk_days"] = _positive_int("days")
+ event_clause = _event_clause() if spec.get("event") else ""
+ if anchor_mode:
+ if event_clause:
+ parts.append(_members_within(now_expr, "lookback", predicate=event_clause))
+ having.append(f"{_performed_before_t0(event_clause, days_param='popk_days')} = 1")
+ else:
+ parts.append(_members_within(now_expr, "popk_days", predicate=event_clause))
+ elif kind == "person_first_seen_within_days":
+ values["popk_days"] = _positive_int("days")
+ # Deliberately not bounded above by the anchor: an imported or backdated event
+ # stream carries person rows created after their events, and an upper bound would
+ # empty the training population for exactly those teams.
+ if anchor_mode:
+ having.append(f"min(toInt(toUnixTimestamp(e.person.created_at))) >= {_T0} - {{popk_days}} * 86400")
+ else:
+ parts.append(f"person.created_at >= {now_expr} - toIntervalDay({{popk_days}})")
+ elif kind == "active_not_performed_target":
+ values["popk_active_days"] = _positive_int("active_within_days")
+ target_clause = _target_clause()
+ if anchor_mode:
+ having.append(f"{_performed_before_t0('', days_param='popk_active_days')} = 1")
+ # A property-filtered action predicate is NULL on rows missing the property. max()
+ # skips NULLs, so a user whose every pre-T0 row is NULL would compare NULL = 0 and
+ # drop out, while the row-mode NOT IN keeps them. Read that NULL as "not performed".
+ having.append(f"ifNull({_performed_before_t0(target_clause)}, 0) = 0")
+ else:
+ parts.append(_members_within(now_expr, "popk_active_days"))
+ parts.append(_members_within(now_expr, "lookback", predicate=target_clause, negate=True))
+ elif kind == "ever_performed_event":
+ event_clause = _event_clause()
+ # In anchor mode the row filter is a cheap superset (performed within the lookback
+ # as of now); the HAVING narrows it to "performed before this user's T0".
+ parts.append(_members_within(now_expr, "lookback", predicate=event_clause))
+ if anchor_mode:
+ having.append(f"{_performed_before_t0(event_clause)} = 1")
+ elif kind == "ever_performed_target":
+ target_clause = _target_clause()
+ parts.append(_members_within(now_expr, "lookback", predicate=target_clause))
+ if anchor_mode:
+ having.append(f"{_performed_before_t0(target_clause)} = 1")
+
+ return _CompiledPopulationKind(where_parts=parts, values=values, anchor_having_parts=having)
+
+
+def _target_condition_for(
+ population: dict[str, Any] | None,
+ *,
+ target_event: str,
+ target_definition: dict[str, Any] | None,
+ team: "Team | None",
+) -> tuple[str | None, dict[str, Any]]:
+ """The compiled target predicate when ``population`` is target-relative, else nothing.
+
+ Resolving an action target reads the Action row, so callers that only need a
+ row-mode population do not pay for it unless a kind consumes it.
+ """
+ if (population or {}).get("kind") not in TARGET_RELATIVE_KINDS:
+ return None, {}
+ return build_target_condition(target_event=target_event, target_definition=target_definition, team=team)
+
+
+def build_target_condition(
+ *,
+ target_event: str,
+ target_definition: dict[str, Any] | None,
+ team: "Team | None",
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build the HogQL boolean fragment deciding whether a single events-table row
+ matches the prediction target, plus any bound parameter values.
+
+ The target is the only place an event target and an action target differ —
+ features, scoring, and inference are all target-agnostic. Two shapes:
+ - event target → ``event = {target}`` (one bound value).
+ - action target → the action's matcher compiled via ``action_to_expr`` and
+ printed back to a self-contained HogQL fragment. The printer inlines and
+ escapes constants, so the action path needs no extra bound values.
+
+ ``target_definition`` selects the shape: ``{"type": "action", "action_id": N}``
+ routes to the action path; anything else (empty, the default, or
+ ``{"type": "event"}``) uses ``target_event``.
+
+ The compiled fragment references events-table columns unqualified (``event``,
+ ``properties``, ``elements_chain``). Every call site embeds it where those
+ columns resolve to the events table — the labeler join (``events e`` plus a
+ person-keyed anchors table that exposes none of them) and the realized-label
+ query (``FROM events``) — so the absent table alias is intentional and safe.
+ """
+ definition = target_definition or {}
+ if definition.get("type") == "action":
+ action_id = definition.get("action_id")
+ if action_id is None:
+ raise ValueError("Action target requires 'action_id' in target_definition")
+ if team is None:
+ raise ValueError("Action target requires a team to resolve the action")
+ # Scope the lookup to the pipeline's project so a foreign action id can't leak across
+ # tenants. Actions live on the project's root team, so a team match would miss them
+ # from any other environment of the same project.
+ action = Action.objects.get(id=action_id, team__project_id=team.project_id)
+ if not action.steps:
+ # action_to_expr compiles an empty step list to a constant true, which would label
+ # every event in the horizon a positive.
+ raise ValueError(f"Action target {action_id} has no steps, so it matches no events")
+ return f"({action_to_expr(action).to_hogql()})", {}
+ return "event = {target}", {"target": target_event}
+
+
+def _build_labeled_users_cte(
+ *,
+ target_event: str,
+ target_definition: dict[str, Any] | None,
+ team: "Team | None",
+ horizon_days: int,
+ lookback_days: int,
+ training_population: dict[str, Any] | None,
+ sample_limit: int | None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build the WITH clause that materialises the labeled_users table:
+ labeled_users(person_id, t0_ts, positive)
+ 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.
+
+ sample_limit caps user_window for fast wizard previews; None = full
+ materialization (trainer).
+ """
+ training_properties = (training_population or {}).get("properties", []) if training_population else []
+ compiled_filters = _compile_population_filters(training_properties)
+ target_cond, target_values = build_target_condition(
+ 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()
+ # 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)}"
+ if sample_limit is not None
+ else ""
+ )
+
+ # One aggregate over the conjunction, not one per filter: inference ANDs the event
+ # filters on a single row, so training must require one pre-T0 event that satisfies all.
+ having_parts: list[str] = []
+ if compiled_filters.event_parts:
+ event_predicate = " AND ".join(compiled_filters.event_parts)
+ having_parts.append(f"{_performed_before_t0(f' AND ({event_predicate})')} = 1")
+ having_parts.extend(compiled_kind.anchor_having_parts)
+ anchor_having = f"\n HAVING {' AND '.join(having_parts)}" if having_parts else ""
+
+ # ifNull on the label: a property-filtered action predicate is NULL on rows that lack
+ # 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.
+ 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(){training_clause}{identified_clause}
+ GROUP BY person_id
+ HAVING first_ts < cutoff_ts{limit_clause}
+ ),
+ user_t0 AS (
+ SELECT
+ person_id,
+ first_ts
+ + intDiv((cutoff_ts - first_ts) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)
+ AS t0_ts
+ FROM user_window
+ ),
+ labeled_users AS (
+ SELECT
+ u.person_id AS person_id,
+ u.t0_ts AS t0_ts,
+ ifNull(max(
+ {target_cond}
+ AND toInt(toUnixTimestamp(e.timestamp)) >= u.t0_ts
+ AND toInt(toUnixTimestamp(e.timestamp)) < u.t0_ts + ({{horizon}} * 86400)
+ ), 0) AS positive
+ 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()
+ GROUP BY u.person_id, u.t0_ts{anchor_having}
+ )
+ """
+ values: dict[str, Any] = {
+ "horizon": horizon_days,
+ "lookback": lookback_days,
+ **target_values,
+ **compiled_filters.values,
+ **compiled_kind.values,
+ }
+ return cte, values
+
+
+def build_random_t0_labeler_sql(
+ *,
+ target_event: str,
+ horizon_days: int,
+ lookback_days: int,
+ training_population: dict[str, Any] | None,
+ sample_limit: int | None = None,
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build a HogQL query that returns one row of (eligible, positives) for a
+ random-T0-per-user labeler. Used by the wizard for live base-rate feedback.
+
+ eligible: users in the training_population with at least one event before
+ now - horizon_days (so a horizon window fits in the data).
+ positives: of those, users who fire target_event in [T0, T0 + horizon).
+
+ With sample_limit=None this gives the trainer's actual eligible count;
+ with sample_limit=N it gives an unbiased estimator computed over N users.
+ """
+ cte, values = _build_labeled_users_cte(
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ horizon_days=horizon_days,
+ lookback_days=lookback_days,
+ training_population=training_population,
+ sample_limit=sample_limit,
+ )
+ sql = f"""
+ {cte}
+ SELECT
+ count() AS eligible,
+ sum(positive) AS positives
+ FROM labeled_users
+ """
+ return sql, values
+
+
+def build_eligible_count_sql(
+ *,
+ horizon_days: int,
+ lookback_days: int,
+ training_population: dict[str, Any] | None,
+ target_event: str = "",
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> 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
+ the full population size, not the sampled subset.
+
+ Returns two columns: ``eligible`` (the v1 headline — restricted to identified
+ users when IDENTIFIED_USERS_ONLY is on) and ``eligible_all`` (the same count
+ without the identified restriction). The caller divides the two to detect a
+ 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)
+ # 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.
+ target_cond, target_values = _target_condition_for(
+ 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
+
+ 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(){training_clause}
+ """
+ values: dict[str, Any] = {
+ "horizon": horizon_days,
+ "lookback": lookback_days,
+ **target_values,
+ **train_values,
+ **compiled_kind.values,
+ }
+ return sql, values
+
+
+def build_inference_anchors_sql(
+ *,
+ lookback_days: int,
+ inference_population: dict[str, Any] | None,
+ cutoff_ts: int | None = None,
+ target_event: str = "",
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build a HogQL query producing (person_id, cutoff_ts) rows for scoring.
+
+ cutoff_ts defaults to now() for every row — at inference time we score "the
+ 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).
+
+ 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)
+
+ # 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()"
+ cutoff_select = "toInt({cutoff_ts})" if cutoff_ts is not None else "toInt(toUnixTimestamp(now()))"
+
+ # Row mode anchored at the cutoff: population membership is decided as of the
+ # scoring instant, mirroring how training decides it as of each user's T0.
+ target_cond, target_values = _target_condition_for(
+ inference_population, target_event=target_event, target_definition=target_definition, team=team
+ )
+ 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}{inf_clause}{identified_clause}
+ """
+ values: dict[str, Any] = {
+ "lookback": lookback_days,
+ **target_values,
+ **inf_values,
+ **compiled_kind.values,
+ }
+ if cutoff_ts is not None:
+ values["cutoff_ts"] = cutoff_ts
+ return sql, values
+
+
+_LINE_COMMENT_STARTS = ("--", "//")
+_ANCHORS_PLACEHOLDER = "{anchors}"
+
+
+def _rewrite_outside_literals(sql: str, *, placeholder: str | None = None, replacement: str = "") -> str:
+ """
+ One quote-aware pass over HogQL text: drop ``--`` / ``//`` line comments and
+ ``/* */`` block comments, and replace ``placeholder`` where it appears in code.
+
+ Single-quoted strings, double-quoted and backtick identifiers are copied
+ verbatim, honoring both the doubled-quote and the backslash escape the HogQL
+ lexer accepts, so a comment marker or a placeholder inside a literal is left
+ alone: the literal is a feature value, not a table reference.
+ """
+ out: list[str] = []
+ i = 0
+ n = len(sql)
+ quote: str | None = None # one of ' " ` when inside a literal
+ while i < n:
+ ch = sql[i]
+ if quote is not None:
+ out.append(ch)
+ if ch == "\\" and i + 1 < n:
+ out.append(sql[i + 1])
+ i += 2
+ continue
+ if ch == quote:
+ if i + 1 < n and sql[i + 1] == quote:
+ out.append(quote)
+ i += 2
+ continue
+ quote = None
+ i += 1
+ continue
+ if ch in ("'", '"', "`"):
+ quote = ch
+ out.append(ch)
+ i += 1
+ continue
+ if sql.startswith(_LINE_COMMENT_STARTS, i):
+ i += 2
+ while i < n and sql[i] != "\n":
+ i += 1
+ continue # leave the newline so adjacent tokens don't fuse
+ if sql.startswith("/*", i):
+ close = sql.find("*/", i + 2)
+ i = n if close < 0 else close + 2
+ out.append(" ") # block comment may sit mid-expression; keep a separator
+ continue
+ if placeholder and sql.startswith(placeholder, i):
+ out.append(replacement)
+ i += len(placeholder)
+ continue
+ out.append(ch)
+ i += 1
+ return "".join(out)
+
+
+def strip_sql_comments(sql: str) -> str:
+ """
+ Remove line and block comments from HogQL, leaving string/identifier literals intact.
+
+ Agent-authored feature SQL routinely carries comments. Blindly substituting
+ ``{anchors}`` with a multi-line subquery that happens to land inside a line
+ comment injects newlines that escape the comment and corrupt the parse, and a
+ comment can also swallow the rest of a line it was never meant to. Stripping
+ comments before substitution sidesteps both.
+ """
+ return _rewrite_outside_literals(sql)
+
+
+def _substitute_anchors(feature_sql: str, anchors_subquery: str) -> str:
+ """
+ Substitute the agent's `{anchors}` placeholder with the actual per-user
+ cutoff subquery. The contract from Step B's static validator guarantees
+ the placeholder is present.
+
+ Comments are stripped in the same pass so a placeholder sitting in (or
+ adjacent to) a comment can't break the substituted SQL, and a placeholder
+ inside a literal is kept as the value it is. A trailing statement
+ terminator is dropped because the training path nests the result as a
+ derived table, where a ``;`` ends the statement early.
+ """
+ substituted = _rewrite_outside_literals(
+ feature_sql, placeholder=_ANCHORS_PLACEHOLDER, replacement=anchors_subquery
+ ).rstrip()
+ return substituted[:-1] if substituted.endswith(";") else substituted
+
+
+def build_training_features_sql(
+ *,
+ feature_sql: str,
+ target_event: str,
+ horizon_days: int,
+ lookback_days: int,
+ training_population: dict[str, Any] | None,
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build the composite training-time query:
+ labeled_users CTE + labeled_anchors (adds fold)
+ + agent's feature_sql (with {anchors} substituted to per-user T0)
+ + JOIN back to labels/fold so each feature row has (__label, __fold)
+
+ Caller substitutes {lookback_days} in feature_sql before calling. Returns
+ one row per eligible user with the agent's feature columns plus __label
+ and __fold for the train/holdout split.
+ """
+ cte, values = _build_labeled_users_cte(
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ horizon_days=horizon_days,
+ lookback_days=lookback_days,
+ training_population=training_population,
+ sample_limit=None,
+ )
+ anchors_subquery = "(SELECT person_id, t0_ts AS cutoff_ts FROM labeled_anchors)"
+ substituted_feature_sql = _substitute_anchors(feature_sql, anchors_subquery)
+
+ sql = f"""
+ {cte},
+ labeled_anchors AS (
+ SELECT
+ person_id,
+ t0_ts,
+ positive,
+ toInt(bitAnd(cityHash64(concat('fold:', toString(person_id))), 2147483647)) % {NUM_FOLDS} AS fold
+ FROM labeled_users
+ )
+ SELECT
+ f.*,
+ la.positive AS __label,
+ la.fold AS __fold
+ FROM (
+ {substituted_feature_sql}
+ ) f
+ LEFT JOIN labeled_anchors la ON f.distinct_id = la.person_id
+ """
+ return sql, values
+
+
+def build_inference_features_sql(
+ *,
+ feature_sql: str,
+ lookback_days: int,
+ inference_population: dict[str, Any] | None,
+ cutoff_ts: int | None = None,
+ target_event: str = "",
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build the inference-time query: the agent's feature_sql with {anchors}
+ substituted with the inference anchors (cutoff_ts = now() per user, or a
+ backdated instant when ``cutoff_ts`` is given for a historical backfill).
+ Returns one row per eligible scoring user with the agent's feature
+ columns — no labels, no fold.
+
+ Caller substitutes {lookback_days} in feature_sql before calling.
+ """
+ anchors_sql, anchors_values = build_inference_anchors_sql(
+ lookback_days=lookback_days,
+ inference_population=inference_population,
+ cutoff_ts=cutoff_ts,
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ )
+ # Wrap the inference anchors query as the {anchors} subquery — agent's
+ # feature_sql references columns (person_id, cutoff_ts) just like training.
+ anchors_subquery = f"({anchors_sql.strip()})"
+ substituted_feature_sql = _substitute_anchors(feature_sql, anchors_subquery)
+ return substituted_feature_sql, anchors_values
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
new file mode 100644
index 000000000000..c95a171709b4
--- /dev/null
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -0,0 +1,442 @@
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import (
+ APIBaseTest,
+ BaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ _create_person,
+ flush_persons_and_events,
+)
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQuery
+
+from posthog.hogql_queries.query_runner import ExecutionMode
+
+from products.autoresearch.backend.dataset.labeling import (
+ _build_labeled_users_cte,
+ _build_population_conditions,
+ _build_population_kind_conditions,
+ _substitute_anchors,
+ build_eligible_count_sql,
+ build_inference_anchors_sql,
+ build_inference_features_sql,
+ build_random_t0_labeler_sql,
+ strip_sql_comments,
+)
+from products.autoresearch.backend.query import run_hogql_rows
+
+
+class TestStripSqlComments(BaseTest):
+ @parameterized.expand(
+ [
+ ("line_comment", "SELECT a -- the count\nFROM t", "SELECT a \nFROM t"),
+ ("block_comment", "SELECT a /* inline */ FROM t", "SELECT a FROM t"),
+ ("trailing_line_comment", "SELECT a FROM t -- trailing", "SELECT a FROM t "),
+ ("double_slash_line_comment", "SELECT a // the count\nFROM t", "SELECT a \nFROM t"),
+ ("no_comment", "SELECT a FROM t", "SELECT a FROM t"),
+ ]
+ )
+ def test_strips_comments(self, _name: str, sql: str, expected: str) -> None:
+ self.assertEqual(strip_sql_comments(sql), expected)
+
+ @parameterized.expand(
+ [
+ ("double_dash_inside_string_literal", "SELECT 'a -- b' AS x FROM t"),
+ ("doubled_quote_inside_string", "SELECT 'it''s -- fine' AS x FROM t"),
+ ("backslash_quote_inside_string", "SELECT 'it\\'s -- fine' AS x FROM t"),
+ ("block_comment_markers_inside_string", "SELECT '/* not a comment */' AS x FROM t"),
+ ("double_dash_inside_backtick_identifier", "SELECT `weird--name` FROM t"),
+ ]
+ )
+ def test_preserves_literals(self, _name: str, sql: str) -> None:
+ self.assertEqual(strip_sql_comments(sql), sql)
+
+
+class TestSubstituteAnchors(BaseTest):
+ def test_placeholder_in_line_comment_does_not_corrupt_substitution(self) -> None:
+ # A multi-line anchors subquery substituted into a `--` comment would
+ # escape the comment and break the parse — stripping comments first avoids it.
+ feature_sql = "SELECT a.person_id AS distinct_id\n-- read FROM {anchors} a here\nFROM {anchors} a"
+ anchors = "(SELECT person_id, t0_ts AS cutoff_ts\nFROM labeled_anchors)"
+ result = _substitute_anchors(feature_sql, anchors)
+ self.assertNotIn("--", result)
+ # The real FROM {anchors} got substituted; the commented one was removed.
+ self.assertEqual(result.count("labeled_anchors"), 1)
+
+ def test_substitutes_all_real_occurrences(self) -> None:
+ feature_sql = "SELECT * FROM {anchors} a JOIN {anchors} b ON a.person_id = b.person_id"
+ result = _substitute_anchors(feature_sql, "(SELECT 1)")
+ self.assertEqual(result.count("(SELECT 1)"), 2)
+ self.assertNotIn("{anchors}", result)
+
+ def test_placeholder_inside_a_string_literal_is_a_value(self) -> None:
+ feature_sql = "SELECT a.person_id AS distinct_id, '{anchors}' AS source FROM {anchors} a"
+ result = _substitute_anchors(feature_sql, "(SELECT 1)")
+ self.assertEqual(result, "SELECT a.person_id AS distinct_id, '{anchors}' AS source FROM (SELECT 1) a")
+
+ def test_trailing_statement_terminator_is_dropped(self) -> None:
+ # The training path nests the feature SQL as a derived table, where a `;` ends the statement early.
+ result = _substitute_anchors("SELECT a.person_id AS distinct_id FROM {anchors} a;\n", "(SELECT 1)")
+ self.assertEqual(result, "SELECT a.person_id AS distinct_id FROM (SELECT 1) a")
+
+
+class TestBuildInferenceFeaturesSql(BaseTest):
+ def test_comment_in_feature_sql_is_stripped_before_substitution(self) -> None:
+ feature_sql = "SELECT a.person_id AS distinct_id -- {anchors}\nFROM {anchors} a"
+ sql, _values = build_inference_features_sql(
+ feature_sql=feature_sql,
+ lookback_days=30,
+ inference_population=None,
+ )
+ self.assertNotIn("{anchors}", sql)
+ self.assertNotIn("--", sql)
+
+
+class TestPopulationFilterCompilation(SimpleTestCase):
+ # A filter that cannot be compiled must raise: skipping it would silently widen the
+ # population, and inference writes person properties for everyone it scores.
+
+ @parameterized.expand(
+ [
+ ("cohort_type", [{"key": "id", "type": "cohort", "operator": "exact", "value": 123}]),
+ ("unknown_operator", [{"key": "plan", "type": "person", "operator": "regex", "value": "x"}]),
+ ("missing_key", [{"type": "person", "operator": "is_set"}]),
+ ("missing_type", [{"key": "plan", "operator": "exact", "value": "pro"}]),
+ ("non_numeric_threshold", [{"key": "price", "type": "event", "operator": "gt", "value": "cheap"}]),
+ ]
+ )
+ 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)
+
+ @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}])", {}),
+ (
+ "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})",
+ {"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})",
+ {"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}",
+ {"pop_0": 13.0},
+ ),
+ ]
+ )
+ 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)
+
+ def test_empty_allowlist_matches_nobody(self) -> None:
+ parts, _values = _build_population_conditions(
+ [{"key": "plan", "type": "person", "operator": "exact", "value": []}]
+ )
+ self.assertEqual(parts, ["1 = 0"])
+
+ def test_empty_denylist_excludes_nobody(self) -> None:
+ parts, _values = _build_population_conditions(
+ [{"key": "plan", "type": "person", "operator": "is_not", "value": []}]
+ )
+ self.assertEqual(parts, [])
+
+
+class TestPopulationKindCompilation(SimpleTestCase):
+ # Guards against the regression where a semantic population spec ({"kind": ...})
+ # fell through the compiler and silently widened to "all identified users".
+
+ @parameterized.expand(
+ [
+ (
+ "performed_any_event",
+ {"kind": "performed_event_within_days", "days": 30},
+ ["person_id IN (SELECT DISTINCT person_id FROM events"],
+ {"popk_days": 30},
+ ),
+ (
+ "performed_specific_event",
+ {"kind": "performed_event_within_days", "days": 30, "event": "$pageview"},
+ ["person_id IN (SELECT DISTINCT person_id FROM events", "event = {popk_event}"],
+ {"popk_days": 30, "popk_event": "$pageview"},
+ ),
+ (
+ "first_seen",
+ {"kind": "person_first_seen_within_days", "days": 14},
+ ["person.created_at >= now() - toIntervalDay({popk_days})"],
+ {"popk_days": 14},
+ ),
+ (
+ "active_not_performed_target",
+ {"kind": "active_not_performed_target", "active_within_days": 30},
+ ["person_id IN (SELECT DISTINCT person_id FROM events", "person_id NOT IN", "(event = {target})"],
+ {"popk_active_days": 30, "target": "feature_used"},
+ ),
+ (
+ "ever_performed_event",
+ {"kind": "ever_performed_event", "event": "checkout"},
+ ["person_id IN (SELECT DISTINCT person_id FROM events", "event = {popk_event}"],
+ {"popk_event": "checkout"},
+ ),
+ (
+ "ever_performed_target",
+ {"kind": "ever_performed_target"},
+ ["person_id IN (SELECT DISTINCT person_id FROM events", "(event = {target})"],
+ {"target": "feature_used"},
+ ),
+ ]
+ )
+ def test_inference_anchors_filter_kind_population(
+ self,
+ _name: str,
+ population: dict[str, Any],
+ fragments: list[str],
+ expected_values: dict[str, Any],
+ ) -> None:
+ sql, values = build_inference_anchors_sql(
+ lookback_days=90, inference_population=population, target_event="feature_used"
+ )
+ for fragment in fragments:
+ self.assertIn(fragment, sql)
+ for key, expected in expected_values.items():
+ self.assertEqual(values[key], expected)
+
+ def test_eligible_count_filters_kind_population(self) -> None:
+ sql, values = build_eligible_count_sql(
+ horizon_days=7,
+ lookback_days=90,
+ training_population={"kind": "performed_event_within_days", "days": 30},
+ )
+ self.assertIn("person_id IN (SELECT DISTINCT person_id FROM events", sql)
+ self.assertEqual(values["popk_days"], 30)
+
+ def test_inference_backfill_anchors_kind_windows_at_cutoff(self) -> None:
+ sql, _values = build_inference_anchors_sql(
+ lookback_days=90,
+ inference_population={"kind": "performed_event_within_days", "days": 30},
+ cutoff_ts=1_700_000_000,
+ )
+ self.assertIn("timestamp >= fromUnixTimestamp({cutoff_ts}) - toIntervalDay({popk_days})", sql)
+
+ @parameterized.expand(
+ [
+ ("unknown_kind", {"kind": "bogus"}),
+ ("missing_days", {"kind": "performed_event_within_days"}),
+ ("non_int_days", {"kind": "person_first_seen_within_days", "days": "14"}),
+ ("missing_active_days", {"kind": "active_not_performed_target"}),
+ ("missing_event", {"kind": "ever_performed_event"}),
+ ]
+ )
+ def test_uncompilable_kind_raises_instead_of_widening(self, _name: str, population: dict[str, Any]) -> None:
+ with self.assertRaises(ValueError):
+ build_inference_anchors_sql(lookback_days=90, inference_population=population, target_event="x")
+
+ @parameterized.expand(
+ [
+ ("adoption", {"kind": "active_not_performed_target", "active_within_days": 30}),
+ ("repeat", {"kind": "ever_performed_target"}),
+ ]
+ )
+ def test_target_relative_kind_requires_the_target_predicate(self, _name: str, population: dict[str, Any]) -> None:
+ with self.assertRaises(ValueError):
+ _build_population_kind_conditions(population)
+
+
+class TestPopulationKindTrainingSemantics(SimpleTestCase):
+ # Training decides membership per user at T0, never as of now(): deciding it as of
+ # now() admits users on activity after T0 (including the outcome window), and a
+ # row-level "has not performed the target" filter would delete exactly the users
+ # whose post-T0 adoption provides the positive labels.
+
+ _EVENT_TS = "toInt(toUnixTimestamp(e.timestamp))"
+
+ @parameterized.expand(
+ [
+ (
+ "adoption_kind",
+ {"kind": "active_not_performed_target", "active_within_days": 30},
+ [
+ f"HAVING max(({_EVENT_TS} >= u.t0_ts - {{popk_active_days}} * 86400 AND {_EVENT_TS} < u.t0_ts)) = 1",
+ f"ifNull(max(({_EVENT_TS} < u.t0_ts AND (event = {{target}}))), 0) = 0",
+ ],
+ ["NOT IN"],
+ ),
+ (
+ "repeat_target_kind",
+ {"kind": "ever_performed_target"},
+ [f"HAVING max(({_EVENT_TS} < u.t0_ts AND (event = {{target}}))) = 1"],
+ [],
+ ),
+ (
+ "ever_performed_event_uses_the_population_event_not_the_target",
+ {"kind": "ever_performed_event", "event": "signup"},
+ [f"HAVING max(({_EVENT_TS} < u.t0_ts AND event = {{popk_event}})) = 1"],
+ ["AND (event = {target}))) = 1"],
+ ),
+ (
+ "performed_within_days_window_ends_at_t0",
+ {"kind": "performed_event_within_days", "days": 30},
+ [f"HAVING max(({_EVENT_TS} >= u.t0_ts - {{popk_days}} * 86400 AND {_EVENT_TS} < u.t0_ts)) = 1"],
+ ["toIntervalDay({popk_days})"],
+ ),
+ (
+ "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"],
+ ["toIntervalDay({popk_days})"],
+ ),
+ (
+ "event_property_filter_at_t0_person_filter_at_the_scan",
+ {
+ "properties": [
+ {"key": "plan", "type": "event", "operator": "exact", "value": "pro"},
+ {"key": "email", "type": "person", "operator": "is_set"},
+ ]
+ },
+ [
+ "AND (isNotNull(person.properties[{pop_k_1}])) AND person.is_identified",
+ 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"],
+ ),
+ (
+ # Inference ANDs event filters on one row, so training must find one pre-T0 event
+ # that satisfies all of them, not one event per filter.
+ "event_property_filters_are_satisfied_by_one_event",
+ {
+ "properties": [
+ {"key": "plan", "type": "event", "operator": "exact", "value": "pro"},
+ {"key": "country", "type": "event", "operator": "exact", "value": "US"},
+ ]
+ },
+ [
+ f"HAVING max(({_EVENT_TS} < u.t0_ts AND (properties[{{pop_k_0}}] = {{pop_0}}"
+ " AND properties[{pop_k_1}] = {pop_1}))) = 1"
+ ],
+ ["= 1 AND max("],
+ ),
+ ]
+ )
+ def test_membership_is_decided_per_user_at_t0(
+ self, _name: str, training_population: dict[str, Any], expected: list[str], forbidden: list[str]
+ ) -> None:
+ cte, _values = _build_labeled_users_cte(
+ target_event="feature_used",
+ target_definition=None,
+ team=None,
+ horizon_days=7,
+ lookback_days=90,
+ training_population=training_population,
+ sample_limit=None,
+ )
+ for fragment in expected:
+ self.assertIn(fragment, cte)
+ for fragment in forbidden:
+ self.assertNotIn(fragment, cte)
+
+ def test_t0_position_does_not_depend_on_a_moving_modulo(self) -> None:
+ cte, _values = _build_labeled_users_cte(
+ target_event="checkout",
+ target_definition=None,
+ team=None,
+ horizon_days=7,
+ lookback_days=90,
+ training_population=None,
+ sample_limit=None,
+ )
+ self.assertIn(
+ "intDiv((cutoff_ts - first_ts) * toInt(bitAnd(cityHash64(toString(person_id)), 2147483647)), 2147483648)",
+ cte,
+ )
+ self.assertNotIn("% (cutoff_ts - first_ts)", cte)
+
+
+_DAILY_PAGEVIEWS = [("$pageview", days_ago) for days_ago in range(100, 0, -1)]
+
+
+class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):
+ # Executes the labeler for each population shape so the per-user-at-T0 HAVING
+ # predicates are proven to resolve against the events scan, not only to print.
+
+ @parameterized.expand(
+ [
+ (
+ # Every T0 precedes the cutoff (now - horizon), so an adoption three days ago is after
+ # T0, while a target on the user's first day precedes every possible T0.
+ "adoption_keeps_users_who_adopt_after_t0",
+ {"kind": "active_not_performed_target", "active_within_days": 30},
+ {
+ "adopter": [*_DAILY_PAGEVIEWS, ("feature_used", 3)],
+ "prior_user": [("feature_used", 100), *_DAILY_PAGEVIEWS],
+ },
+ 1,
+ ),
+ (
+ "repeat_target_requires_prior_performance",
+ {"kind": "ever_performed_target"},
+ {"repeater": [("feature_used", 100), *_DAILY_PAGEVIEWS], "never": _DAILY_PAGEVIEWS},
+ 1,
+ ),
+ (
+ "performed_within_days",
+ {"kind": "performed_event_within_days", "days": 30, "event": "$pageview"},
+ {"member": _DAILY_PAGEVIEWS},
+ 1,
+ ),
+ ("first_seen", {"kind": "person_first_seen_within_days", "days": 14}, {"member": _DAILY_PAGEVIEWS}, 1),
+ (
+ "event_property",
+ {"properties": [{"key": "plan", "type": "event", "operator": "exact", "value": "pro"}]},
+ {"member": _DAILY_PAGEVIEWS},
+ 1,
+ ),
+ ]
+ )
+ 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
+ ) -> 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)
+ for event, days_ago in events:
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=distinct_id,
+ timestamp=now - timedelta(days=days_ago),
+ properties={"plan": "pro"},
+ )
+ flush_persons_and_events()
+
+ sql, values = build_random_t0_labeler_sql(
+ target_event="feature_used",
+ horizon_days=7,
+ lookback_days=120,
+ training_population=training_population,
+ team=self.team,
+ )
+ rows = run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=sql, values=values),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )
+ assert int(rows[0][0]) == expected
diff --git a/products/autoresearch/backend/dataset/test_target.py b/products/autoresearch/backend/dataset/test_target.py
new file mode 100644
index 000000000000..f4aef6ee161c
--- /dev/null
+++ b/products/autoresearch/backend/dataset/test_target.py
@@ -0,0 +1,126 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+
+from posthog.schema import HogQLQuery
+
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models import Organization, Team
+
+from products.actions.backend.models.action import Action
+from products.autoresearch.backend.dataset.labeling import build_target_condition
+from products.autoresearch.backend.query import run_hogql_rows
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+
+
+class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):
+ def test_event_target_emits_bound_predicate(self):
+ cond, values = build_target_condition(target_event="$pageview", target_definition=None, team=None)
+ assert cond == "event = {target}"
+ assert values == {"target": "$pageview"}
+
+ def test_event_type_definition_still_uses_target_event(self):
+ cond, values = build_target_condition(
+ target_event="signed_up", target_definition={"type": "event"}, team=self.team
+ )
+ assert cond == "event = {target}"
+ assert values == {"target": "signed_up"}
+
+ def test_action_target_compiles_to_self_contained_fragment(self):
+ action = Action.objects.create(
+ team=self.team,
+ name="Interacted with file",
+ steps_json=[{"event": "uploaded_file"}, {"event": "downloaded_file"}],
+ )
+ cond, values = build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
+ )
+ # Self-contained: constants inlined + escaped by the printer, so no bound values.
+ assert values == {}
+ assert "uploaded_file" in cond
+ assert "downloaded_file" in cond
+
+ def test_action_target_requires_action_id(self):
+ with self.assertRaises(ValueError):
+ build_target_condition(target_event="", target_definition={"type": "action"}, team=self.team)
+
+ def test_action_target_requires_team(self):
+ with self.assertRaises(ValueError):
+ build_target_condition(target_event="", target_definition={"type": "action", "action_id": 1}, team=None)
+
+ def test_action_target_is_team_scoped(self):
+ other_org = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_org, name="Other")
+ action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
+ # Resolving a foreign action against self.team must not leak it.
+ with self.assertRaises(Action.DoesNotExist):
+ build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
+ )
+
+ def test_action_target_resolves_from_a_secondary_environment(self):
+ # Actions are stored on the project's root team, so a pipeline in another
+ # environment of the same project must still find them.
+ environment = Team.objects.create(organization=self.organization, project=self.project, name="Env 2")
+ action = Action.objects.create(team=self.team, name="Upload", steps_json=[{"event": "uploaded_file"}])
+ cond, _values = build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=environment
+ )
+ assert "uploaded_file" in cond
+
+ def test_action_target_with_no_steps_is_rejected(self):
+ # action_to_expr compiles an empty step list to a constant true, which would make
+ # every event in the horizon a positive label.
+ action = Action.objects.create(team=self.team, name="Empty", steps_json=[])
+ with self.assertRaises(ValueError):
+ build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
+ )
+
+
+class TestTargetConditionAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):
+ def _count(self, cond: str, values: dict) -> int:
+ sql = f"SELECT count() FROM events WHERE {cond}"
+ rows = run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=sql, values=values),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )
+ return int(rows[0][0]) if rows else 0
+
+ def test_action_predicate_selects_action_matching_events(self):
+ _create_person(team_id=self.team.pk, distinct_ids=["u1"])
+ for event in ["uploaded_file", "uploaded_file", "downloaded_file", "$pageview", "$pageview", "$pageview"]:
+ _create_event(team=self.team, event=event, distinct_id="u1")
+ flush_persons_and_events()
+
+ action = Action.objects.create(
+ team=self.team,
+ name="Interacted with file",
+ steps_json=[{"event": "uploaded_file"}, {"event": "downloaded_file"}],
+ )
+
+ action_cond, action_values = build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
+ )
+ event_cond, event_values = build_target_condition(
+ target_event="$pageview", target_definition=None, team=self.team
+ )
+
+ # 2 uploaded_file + 1 downloaded_file match the action; 3 $pageview match the event target.
+ assert self._count(action_cond, action_values) == 3
+ assert self._count(event_cond, event_values) == 3
+
+ def test_action_with_property_filter(self):
+ _create_person(team_id=self.team.pk, distinct_ids=["u2"])
+ _create_event(team=self.team, event="uploaded_file", distinct_id="u2", properties={"size": "large"})
+ _create_event(team=self.team, event="uploaded_file", distinct_id="u2", properties={"size": "small"})
+ flush_persons_and_events()
+
+ action = Action.objects.create(
+ team=self.team,
+ name="Large upload",
+ steps_json=[{"event": "uploaded_file", "properties": [{"key": "size", "value": "large", "type": "event"}]}],
+ )
+ cond, values = build_target_condition(
+ target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
+ )
+ assert self._count(cond, values) == 1
diff --git a/products/autoresearch/backend/query.py b/products/autoresearch/backend/query.py
new file mode 100644
index 000000000000..9e26085176a3
--- /dev/null
+++ b/products/autoresearch/backend/query.py
@@ -0,0 +1,67 @@
+from typing import Any
+
+from posthog.schema import CacheMissResponse, HogQLQuery, QueryStatusResponse
+
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+
+class AutoresearchQueryError(Exception):
+ pass
+
+
+@frozen
+class HogQLResult:
+ columns: list[str]
+ rows: list[list[Any]]
+ # True when the runner's default paginator cut the result short. A query with no
+ # top-level LIMIT is capped at 100 rows, so a caller that materializes rows must
+ # either bound the query itself or refuse a truncated result.
+ has_more: bool = False
+
+ def as_dicts(self) -> list[dict[str, Any]]:
+ return [dict(zip(self.columns, row)) for row in self.rows]
+
+
+def run_hogql(
+ *,
+ team: Team,
+ query: HogQLQuery,
+ user: User | None = None,
+ execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+) -> HogQLResult:
+ """Run a HogQL query under a blocking execution mode and return its columns and rows.
+
+ `user` is the person HogQL applies access control for: the request user on an API
+ path, and the pipeline's creator on a background path (scoring, online validation),
+ as `posthog/hogql/ACCESS_CONTROL.md` prescribes for jobs that act for a user. With
+ no user HogQL fails closed: it denies every warehouse table and applies only the
+ default property restrictions, so a pipeline can be masked from data its creator
+ may read.
+
+ The runner's return type also covers the cache-miss and async-status shapes that
+ a blocking mode never produces. Raising on those keeps every caller off the union,
+ and keeps "the query returned nothing" distinct from "the query did not run",
+ which callers here read as a real zero.
+ """
+ response = HogQLQueryRunner(query=query, team=team, user=user).run(execution_mode=execution_mode)
+ if isinstance(response, CacheMissResponse | QueryStatusResponse):
+ raise AutoresearchQueryError(f"HogQL query did not execute: got {type(response).__name__}")
+ return HogQLResult(
+ columns=[str(c) for c in (response.columns or [])],
+ rows=response.results or [],
+ has_more=bool(response.hasMore),
+ )
+
+
+def run_hogql_rows(
+ *,
+ team: Team,
+ query: HogQLQuery,
+ user: User | None = None,
+ execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+) -> list[list[Any]]:
+ return run_hogql(team=team, query=query, user=user, execution_mode=execution_mode).rows
diff --git a/products/autoresearch/backend/testing.py b/products/autoresearch/backend/testing.py
new file mode 100644
index 000000000000..45621b40e1cc
--- /dev/null
+++ b/products/autoresearch/backend/testing.py
@@ -0,0 +1,18 @@
+from contextlib import ExitStack
+
+from posthog.models.scoping import team_scope
+
+
+class TeamScopedTestMixin:
+ """Runs each test inside its team's scope.
+
+ The models are fail-closed, so a test that builds fixtures or calls a service
+ function directly has to set the scope that a request, a Temporal activity, or a
+ management command sets in production.
+ """
+
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ stack = ExitStack()
+ stack.enter_context(team_scope(self.team.id)) # type: ignore[attr-defined]
+ self.addCleanup(stack.close) # type: ignore[attr-defined]
diff --git a/tach.toml b/tach.toml
index bf83205f27e9..4dd5c630ea68 100644
--- a/tach.toml
+++ b/tach.toml
@@ -192,6 +192,7 @@ layer = "modules"
path = "products.autoresearch"
depends_on = [
"posthog",
+ "products.actions",
"products.feature_flags",
]
layer = "modules"