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 dataset templates (5/22) (#88793)

Andrew Maguiree78138d9a4f1
diff --git a/products/autoresearch/backend/dataset/templates.py b/products/autoresearch/backend/dataset/templates.py
new file mode 100644
index 000000000000..3a66d560377e
--- /dev/null
+++ b/products/autoresearch/backend/dataset/templates.py
@@ -0,0 +1,354 @@
+"""
+Built-in autoresearch prediction templates.
+
+Each template resolves to the same pipeline config shape as a custom pipeline,
+so validation and creation work identically whether the user started from a template
+or built a fully custom definition.
+
+Population specs use a semantic format compiled to HogQL by
+labeling._build_population_kind_conditions. Supported kinds:
+ performed_event_within_days users who did `event` (any event when omitted) in
+ the last `days` days
+ person_first_seen_within_days users whose first-seen date is within `days` days
+ active_not_performed_target active users (any event in `active_within_days`) who
+ have NOT performed the pipeline's target
+ ever_performed_event users who have performed `event` at least once
+ ever_performed_target users who have performed the pipeline's target at least once
+
+"Ever" and "has not performed" are bounded to the pipeline's training lookback
+window. The target-relative kinds compile against the pipeline's target
+predicate, so an action target matches by its matcher rather than its name.
+Every kind is evaluated per user at T0 during training and as of the cutoff at
+inference — see the compiler's docstring for the semantics.
+
+Templates take an event name as their target. An action target is set through the
+pipeline's `target_definition` at creation, outside template resolution.
+"""
+
+from __future__ import annotations
+
+import re
+import hashlib
+from typing import Any, Optional
+
+from posthog.schema import HogQLQuery
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.autoresearch.backend.dataset.labeling import _identified_users_and_clause
+from products.autoresearch.backend.query import run_hogql_rows
+
+# Checked in this order when resolving an activity event for universal templates
+_PREFERRED_ACTIVITY_EVENTS = ["$pageview", "$screen", "$autocapture"]
+_MAX_ACTIVITY_ALTERNATIVES = 4
+
+# The resolver hands its result to pipeline creation, so it must fit the pipeline's columns:
+# `AutoresearchPipeline.target_event`, `.name` and `.output_person_property` are all 255 wide.
+_PIPELINE_FIELD_MAX_LENGTH = 255
+
+_UNSAFE_PROPERTY_CHARS = re.compile(r"[^a-z0-9._-]+")
+
+
+@frozen
+class AutoresearchTemplate:
+ key: str
+ display_name: str
+ description_template: str
+ default_horizon_days: int
+ output_property_prefix: str
+ requires_user_event: bool # user must supply target_event override
+ requires_activity_resolution: bool # target_event resolved from schema
+ training_population_spec: dict[str, Any]
+ inference_population_spec: dict[str, Any]
+ notes: str = ""
+
+ @property
+ def description(self) -> str:
+ return self.describe(self.default_horizon_days)
+
+ def describe(self, horizon_days: int) -> str:
+ return self.description_template.format(horizon_days=horizon_days)
+
+
+TEMPLATES: dict[str, AutoresearchTemplate] = {
+ "likely_active_soon": AutoresearchTemplate(
+ key="likely_active_soon",
+ display_name="Likely active soon",
+ description_template=(
+ "Predict which active users will be active again in the next {horizon_days} days. "
+ "Works for any product that sends pageview or screen events."
+ ),
+ default_horizon_days=7,
+ output_property_prefix="predicted_p_active_soon",
+ requires_user_event=False,
+ requires_activity_resolution=True,
+ training_population_spec={"kind": "performed_event_within_days", "days": 30},
+ inference_population_spec={"kind": "performed_event_within_days", "days": 30},
+ notes=(
+ "The activity event is resolved from your event schema, preferring $pageview, then $screen, "
+ "then $autocapture, then the custom event with the most identified users. You can override it."
+ ),
+ ),
+ "at_risk_of_inactivity": AutoresearchTemplate(
+ key="at_risk_of_inactivity",
+ display_name="At risk of inactivity",
+ description_template=(
+ "Find users who are unlikely to be active in the next {horizon_days} days. "
+ "The model predicts the probability of activity, so users with a low score are the at-risk group."
+ ),
+ default_horizon_days=14,
+ output_property_prefix="predicted_p_active_next",
+ requires_user_event=False,
+ requires_activity_resolution=True,
+ training_population_spec={"kind": "performed_event_within_days", "days": 60},
+ inference_population_spec={"kind": "performed_event_within_days", "days": 60},
+ notes=(
+ "The score is the probability of activity. Build the at-risk cohort with a low threshold "
+ "on the score, for example below 0.2, instead of modeling the absence of an event."
+ ),
+ ),
+ "return_after_first_use": AutoresearchTemplate(
+ key="return_after_first_use",
+ display_name="Likely to return after first use",
+ description_template=(
+ "Predict which new users will be active again within {horizon_days} days. "
+ "Uses the person's first-seen date, so it does not need a signup event."
+ ),
+ default_horizon_days=7,
+ output_property_prefix="predicted_p_return_after_first_use",
+ requires_user_event=False,
+ requires_activity_resolution=True,
+ training_population_spec={"kind": "person_first_seen_within_days", "days": 14},
+ inference_population_spec={"kind": "person_first_seen_within_days", "days": 14},
+ notes=(
+ "The population is users first seen in the last 14 days. The activity event is resolved "
+ "from your event schema. Any activity after the sampled anchor point counts, including "
+ "activity later in the same first session."
+ ),
+ ),
+ "feature_adoption": AutoresearchTemplate(
+ key="feature_adoption",
+ display_name="Likely to adopt a feature",
+ description_template=(
+ "Predict which active users will use a selected feature for the first time within {horizon_days} days. "
+ "Choose the feature's event."
+ ),
+ default_horizon_days=14,
+ output_property_prefix="predicted_p_adopt",
+ requires_user_event=True,
+ requires_activity_resolution=False,
+ training_population_spec={"kind": "active_not_performed_target", "active_within_days": 30},
+ inference_population_spec={"kind": "active_not_performed_target", "active_within_days": 30},
+ notes=(
+ "The population is users active in the last 30 days who have not performed the selected event "
+ "within the training lookback window. Use before that window does not exclude a user."
+ ),
+ ),
+ "repeat_key_behavior": AutoresearchTemplate(
+ key="repeat_key_behavior",
+ display_name="Likely to repeat a key behavior",
+ description_template=(
+ "Predict which users who have already done a key action will do it again within {horizon_days} days. "
+ "Useful for feature retention, power usage, and repeat purchases."
+ ),
+ default_horizon_days=7,
+ output_property_prefix="predicted_p_repeat",
+ requires_user_event=True,
+ requires_activity_resolution=False,
+ training_population_spec={"kind": "ever_performed_target"},
+ inference_population_spec={"kind": "ever_performed_target"},
+ notes=(
+ "The population is users who performed the selected event at least once within the training "
+ "lookback window."
+ ),
+ ),
+}
+
+
+def _is_activity_candidate(event: str) -> bool:
+ # PostHog's own events carry a `$` prefix. Outside the preferred activity events they are
+ # SDK bookkeeping ($identify, $feature_flag_called, $groupidentify, ...), not user behavior.
+ if event in _PREFERRED_ACTIVITY_EVENTS:
+ return True
+ return not event.startswith("$") and len(event) <= _PIPELINE_FIELD_MAX_LENGTH
+
+
+def resolve_activity_event(team: Team, user: Optional[User] = None) -> tuple[Optional[str], list[str]]:
+ """
+ Discover the best activity event for universal activity templates.
+
+ Ranks the last 30 days of events by identified persons, checks for preferred
+ activity events ($pageview, $screen, $autocapture) in priority order, and falls
+ back to the custom event with the widest identified-person coverage.
+
+ Returns (resolved_event, alternatives) where alternatives are other viable
+ events the user can choose as an override. `resolved_event` is None when the
+ team has no candidate. `user` is the person HogQL applies access control for;
+ see `query.run_hogql`.
+ """
+ # Training and scoring only ever see identified users, so rank candidates on that
+ # same population: anonymous-only traffic must not choose the activity event.
+ identified_clause = _identified_users_and_clause()
+ preferred_literal = ", ".join(f"'{event}'" for event in _PREFERRED_ACTIVITY_EVENTS)
+ # Preferred events sort first so the row limit cannot drop them on teams with many event names.
+ query = HogQLQuery(
+ query=f"""
+ SELECT event, uniq(person_id) AS c
+ FROM events
+ WHERE timestamp >= now() - toIntervalDay(30)
+ AND timestamp < now(){identified_clause}
+ AND (event IN ({preferred_literal}) OR event NOT LIKE '$%')
+ GROUP BY event
+ ORDER BY event IN ({preferred_literal}) DESC, c DESC, event
+ LIMIT 100
+ """,
+ )
+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
+ rows = run_hogql_rows(team=team, query=query, user=user)
+
+ seen: dict[str, int] = {}
+ for row in rows or []:
+ event_name = str(row[0])
+ if _is_activity_candidate(event_name):
+ seen[event_name] = int(row[1] or 0)
+ ranked = [event for event, _ in sorted(seen.items(), key=lambda item: (-item[1], item[0]))]
+
+ resolved = next((preferred for preferred in _PREFERRED_ACTIVITY_EVENTS if preferred in seen), None)
+ if resolved is None:
+ if not ranked:
+ return None, []
+ resolved = ranked[0]
+
+ alternatives = [event for event in _PREFERRED_ACTIVITY_EVENTS if event in seen and event != resolved]
+ for event in ranked:
+ if len(alternatives) >= _MAX_ACTIVITY_ALTERNATIVES:
+ break
+ if event != resolved and event not in alternatives:
+ alternatives.append(event)
+ return resolved, alternatives
+
+
+@frozen
+class ResolvedTemplate:
+ template_key: str
+ display_name: str
+ description: str
+ target_event: str
+ resolved_activity_event: Optional[str]
+ activity_event_alternatives: list[str]
+ horizon_days: int
+ training_population: dict[str, Any]
+ inference_population: dict[str, Any]
+ output_person_property: str
+ suggested_name: str
+ notes: str
+
+
+def _target_digest(target_event: str) -> str:
+ # Upper case on purpose: a normalized name is all lower case, so a name that carries a
+ # digest can never equal an event name that needed no normalization.
+ # Twelve hex characters give 48 bits, so two distinct targets that normalize alike do not
+ # share one person property in practice. A six-character prefix collides within a few
+ # thousand names.
+ return hashlib.sha256(target_event.encode()).hexdigest()[:12].upper()
+
+
+def _safe_target_name(target_event: str) -> str:
+ raw = target_event.lstrip("$")
+ safe = _UNSAFE_PROPERTY_CHARS.sub("_", raw.lower()).strip("_") or "target"
+ if safe == raw:
+ return safe
+ # Normalization is lossy ("Checkout Started" and "checkout_started" collapse to one name),
+ # so a stable digest of the original keeps two such targets on separate person properties.
+ return f"{safe}_{_target_digest(target_event)}"
+
+
+def _output_person_property(prefix: str, target_event: str, horizon_days: int) -> str:
+ # The target and the horizon are both part of the name: two pipelines that share one
+ # but not the other must not $set the same person property and clobber each other's scores.
+ suffix = f"_{horizon_days}d"
+ name = f"{prefix}_{_safe_target_name(target_event)}"
+ room = _PIPELINE_FIELD_MAX_LENGTH - len(suffix)
+ if len(name) > room:
+ digest = _target_digest(target_event)
+ name = f"{name[: room - len(digest) - 1].rstrip('_')}_{digest}"
+ return f"{name}{suffix}"
+
+
+def resolve_template(
+ team: Team,
+ template_key: str,
+ target_event_override: Optional[str] = None,
+ horizon_days_override: Optional[int] = None,
+ user: Optional[User] = None,
+) -> ResolvedTemplate:
+ """
+ Resolve a template key + optional overrides into a concrete pipeline config.
+
+ Raises ValueError if template_key is unknown, a required override is missing, the
+ horizon is not positive, or no activity event can be resolved for the team.
+ The returned ResolvedTemplate can be passed directly to pipeline creation.
+ """
+ template = TEMPLATES.get(template_key)
+ if template is None:
+ raise ValueError(f"Unknown template '{template_key}'. Available: {', '.join(TEMPLATES)}")
+
+ if template.requires_user_event and not target_event_override:
+ raise ValueError(
+ f"Template '{template_key}' requires a target_event override. Provide the event name you want to predict."
+ )
+
+ if horizon_days_override is not None and horizon_days_override < 1:
+ raise ValueError("horizon_days must be at least 1.")
+
+ if target_event_override and len(target_event_override) > _PIPELINE_FIELD_MAX_LENGTH:
+ raise ValueError(f"target_event must be at most {_PIPELINE_FIELD_MAX_LENGTH} characters.")
+
+ resolved_activity: Optional[str] = None
+ alternatives: list[str] = []
+
+ if template.requires_activity_resolution:
+ resolved_activity, alternatives = resolve_activity_event(team, user=user)
+ target_event = target_event_override or resolved_activity or ""
+ if not target_event:
+ raise ValueError(
+ f"Template '{template_key}' could not resolve an activity event: no identified users "
+ "sent a usable event in the last 30 days. Provide target_event to choose one."
+ )
+ else:
+ target_event = target_event_override or ""
+
+ horizon_days = horizon_days_override if horizon_days_override is not None else template.default_horizon_days
+
+ training_population = dict(template.training_population_spec)
+ inference_population = dict(template.inference_population_spec)
+ if template.requires_activity_resolution:
+ # "Active" means the resolved activity event, for the population as much as for the label.
+ # Without the event key the kind admits anyone who sent any event, bookkeeping included.
+ for population in (training_population, inference_population):
+ if population["kind"] == "performed_event_within_days":
+ population["event"] = target_event
+
+ if template.requires_user_event:
+ safe_label = target_event.lstrip("$").replace("_", " ")
+ suggested_name = f"{template.display_name}: {safe_label}"[:_PIPELINE_FIELD_MAX_LENGTH]
+ else:
+ suggested_name = template.display_name
+
+ return ResolvedTemplate(
+ template_key=template_key,
+ display_name=template.display_name,
+ description=template.describe(horizon_days),
+ target_event=target_event,
+ resolved_activity_event=resolved_activity,
+ activity_event_alternatives=alternatives,
+ horizon_days=horizon_days,
+ training_population=training_population,
+ inference_population=inference_population,
+ output_person_property=_output_person_property(template.output_property_prefix, target_event, horizon_days),
+ suggested_name=suggested_name,
+ notes=template.notes,
+ )
diff --git a/products/autoresearch/backend/dataset/test_templates.py b/products/autoresearch/backend/dataset/test_templates.py
new file mode 100644
index 000000000000..487c1e639f0b
--- /dev/null
+++ b/products/autoresearch/backend/dataset/test_templates.py
@@ -0,0 +1,233 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.dataset.labeling import _build_population_kind_conditions
+from products.autoresearch.backend.dataset.templates import (
+ TEMPLATES,
+ ResolvedTemplate,
+ resolve_activity_event,
+ resolve_template,
+)
+
+
+class TestTemplateDefinitions(SimpleTestCase):
+ def test_all_five_templates_present(self) -> None:
+ self.assertEqual(
+ set(TEMPLATES.keys()),
+ {
+ "likely_active_soon",
+ "at_risk_of_inactivity",
+ "return_after_first_use",
+ "feature_adoption",
+ "repeat_key_behavior",
+ },
+ )
+
+ @parameterized.expand(list(TEMPLATES.keys()))
+ def test_template_has_required_fields(self, key: str) -> None:
+ t = TEMPLATES[key]
+ self.assertTrue(t.display_name)
+ self.assertIn(f"{t.default_horizon_days} days", t.description)
+ self.assertNotIn("{", t.description)
+ self.assertGreater(t.default_horizon_days, 0)
+ self.assertTrue(t.output_property_prefix)
+ self.assertIsInstance(t.training_population_spec, dict)
+ self.assertIsInstance(t.inference_population_spec, dict)
+
+ @parameterized.expand(
+ [
+ ("likely_active_soon", 7, False, True),
+ ("at_risk_of_inactivity", 14, False, True),
+ ("return_after_first_use", 7, False, True),
+ ("feature_adoption", 14, True, False),
+ ("repeat_key_behavior", 7, True, False),
+ ]
+ )
+ def test_template_config(
+ self,
+ key: str,
+ expected_horizon: int,
+ requires_user_event: bool,
+ requires_activity_resolution: bool,
+ ) -> None:
+ t = TEMPLATES[key]
+ self.assertEqual(t.default_horizon_days, expected_horizon)
+ self.assertEqual(t.requires_user_event, requires_user_event)
+ self.assertEqual(t.requires_activity_resolution, requires_activity_resolution)
+
+
+class TestTemplateSpecsCompile(SimpleTestCase):
+ # Drift guard: every template's population spec must have a compiler branch in
+ # labeling.py, in both row mode (inference/eligible count) and anchor mode (training).
+
+ @parameterized.expand(list(TEMPLATES.keys()))
+ def test_population_specs_compile_in_both_modes(self, key: str) -> None:
+ t = TEMPLATES[key]
+ 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(anchor.anchor_having_parts)
+
+
+class TestResolveActivityEvent(SimpleTestCase):
+ def test_ranks_candidates_over_identified_users_only(self) -> None:
+ # Training and scoring only see identified users, so an event that only anonymous
+ # traffic emits must not be chosen as the activity signal.
+ team = MagicMock()
+ team.pk = 1
+ user = MagicMock()
+ with patch(
+ "products.autoresearch.backend.dataset.templates.run_hogql_rows",
+ return_value=[["$pageview", 10]],
+ ) as mock_run:
+ resolved, _alternatives = resolve_activity_event(team, user=user)
+ self.assertEqual(resolved, "$pageview")
+ query = mock_run.call_args.kwargs["query"].query
+ self.assertIn("person.is_identified", query)
+ self.assertIn("uniq(person_id)", query)
+ self.assertIs(mock_run.call_args.kwargs["user"], user)
+
+ @parameterized.expand(
+ [
+ # A preferred event wins over a busier custom event; bookkeeping never wins.
+ ([["$identify", 50], ["clicked", 20], ["$pageview", 10]], "$pageview", ["clicked"]),
+ # Equal coverage breaks ties by name, so a cache refresh cannot flip the target.
+ ([["$identify", 50], ["heartbeat", 20], ["clicked", 20]], "clicked", ["heartbeat"]),
+ ([["x" * 300, 40], ["clicked", 20]], "clicked", []),
+ ([["$identify", 50]], None, []),
+ ([], None, []),
+ ]
+ )
+ def test_ranking(self, rows: list[list[object]], expected: str | None, expected_alternatives: list[str]) -> None:
+ with patch("products.autoresearch.backend.dataset.templates.run_hogql_rows", return_value=rows):
+ resolved, alternatives = resolve_activity_event(MagicMock())
+ self.assertEqual(resolved, expected)
+ self.assertEqual(alternatives, expected_alternatives)
+
+
+class TestResolveTemplate(SimpleTestCase):
+ def _make_team(self) -> MagicMock:
+ team = MagicMock()
+ team.pk = 1
+ return team
+
+ def test_unknown_template_raises(self) -> None:
+ with self.assertRaises(ValueError, msg="Unknown template"):
+ resolve_template(self._make_team(), "nonexistent_template")
+
+ def test_feature_adoption_without_target_event_raises(self) -> None:
+ with self.assertRaises(ValueError, msg="requires a target_event override"):
+ resolve_template(self._make_team(), "feature_adoption")
+
+ def test_repeat_key_behavior_without_target_event_raises(self) -> None:
+ with self.assertRaises(ValueError):
+ resolve_template(self._make_team(), "repeat_key_behavior")
+
+ @parameterized.expand([(0,), (-3,)])
+ def test_non_positive_horizon_raises(self, horizon: int) -> None:
+ with self.assertRaises(ValueError, msg="horizon_days must be at least 1"):
+ resolve_template(self._make_team(), "feature_adoption", "signed_up", horizon_days_override=horizon)
+
+ @patch("products.autoresearch.backend.dataset.templates.resolve_activity_event", return_value=(None, []))
+ def test_unresolved_activity_event_raises_without_override(self, _: MagicMock) -> None:
+ with self.assertRaises(ValueError, msg="could not resolve an activity event"):
+ resolve_template(self._make_team(), "likely_active_soon")
+ result = resolve_template(self._make_team(), "likely_active_soon", target_event_override="$screen")
+ self.assertEqual(result.target_event, "$screen")
+
+ @patch(
+ "products.autoresearch.backend.dataset.templates.resolve_activity_event",
+ return_value=("$pageview", ["$screen"]),
+ )
+ def test_likely_active_soon_resolves(self, mock_resolve: MagicMock) -> None:
+ team = self._make_team()
+ user = MagicMock()
+ result = resolve_template(team, "likely_active_soon", user=user)
+ mock_resolve.assert_called_once_with(team, user=user)
+ self.assertIsInstance(result, ResolvedTemplate)
+ self.assertEqual(result.target_event, "$pageview")
+ self.assertEqual(result.resolved_activity_event, "$pageview")
+ self.assertEqual(result.horizon_days, 7)
+ self.assertEqual(result.output_person_property, "predicted_p_active_soon_pageview_7d")
+ self.assertEqual(
+ result.training_population, {"kind": "performed_event_within_days", "days": 30, "event": "$pageview"}
+ )
+ self.assertEqual(result.inference_population["event"], "$pageview")
+
+ @patch("products.autoresearch.backend.dataset.templates.resolve_activity_event", return_value=("$pageview", []))
+ def test_activity_event_override_respected(self, mock_resolve: MagicMock) -> None:
+ result = resolve_template(self._make_team(), "likely_active_soon", target_event_override="$screen")
+ self.assertEqual(result.target_event, "$screen")
+ self.assertEqual(result.training_population["event"], "$screen")
+ self.assertEqual(result.output_person_property, "predicted_p_active_soon_screen_7d")
+ # resolved_activity_event still shows what the schema resolver found
+ self.assertEqual(result.resolved_activity_event, "$pageview")
+
+ @patch("products.autoresearch.backend.dataset.templates.resolve_activity_event", return_value=("$pageview", []))
+ def test_horizon_override_respected(self, _: MagicMock) -> None:
+ result = resolve_template(self._make_team(), "likely_active_soon", horizon_days_override=14)
+ self.assertEqual(result.horizon_days, 14)
+ self.assertIn("14 days", result.description)
+ # Horizon is part of the output property so the same target over a different horizon
+ # does not clobber another pipeline's score.
+ self.assertEqual(result.output_person_property, "predicted_p_active_soon_pageview_14d")
+
+ def test_feature_adoption_with_target_event(self) -> None:
+ result = resolve_template(self._make_team(), "feature_adoption", target_event_override="feature_clicked")
+ self.assertEqual(result.target_event, "feature_clicked")
+ self.assertEqual(result.horizon_days, 14)
+ self.assertEqual(result.output_person_property, "predicted_p_adopt_feature_clicked_14d")
+ self.assertEqual(result.training_population, {"kind": "active_not_performed_target", "active_within_days": 30})
+ self.assertIsNone(result.resolved_activity_event)
+
+ def test_repeat_key_behavior_with_target_event(self) -> None:
+ result = resolve_template(self._make_team(), "repeat_key_behavior", target_event_override="$pageview")
+ self.assertEqual(result.target_event, "$pageview")
+ self.assertEqual(result.training_population, {"kind": "ever_performed_target"})
+ self.assertIn("pageview", result.output_person_property)
+
+ def test_feature_adoption_suggested_name_includes_event(self) -> None:
+ result = resolve_template(self._make_team(), "feature_adoption", target_event_override="my_feature")
+ self.assertIn("my feature", result.suggested_name)
+
+ def test_targets_that_normalize_alike_keep_distinct_properties(self) -> None:
+ lossy = resolve_template(self._make_team(), "feature_adoption", target_event_override="Checkout Started")
+ exact = resolve_template(self._make_team(), "feature_adoption", target_event_override="checkout_started")
+ self.assertTrue(lossy.output_person_property.startswith("predicted_p_adopt_checkout_started_"))
+ self.assertEqual(exact.output_person_property, "predicted_p_adopt_checkout_started_14d")
+ self.assertNotEqual(lossy.output_person_property, exact.output_person_property)
+ # An event literally named like the encoded form of another event still gets its own property.
+ encoded = lossy.output_person_property.removeprefix("predicted_p_adopt_").removesuffix("_14d")
+ literal = resolve_template(self._make_team(), "feature_adoption", target_event_override=encoded)
+ self.assertNotEqual(literal.output_person_property, lossy.output_person_property)
+ # Two lossy names that normalize to the same string rely on the digest alone to stay apart.
+ first = resolve_template(self._make_team(), "feature_adoption", target_event_override="CHEckOUTstARted")
+ second = resolve_template(self._make_team(), "feature_adoption", target_event_override="ChecKoutStARted")
+ self.assertNotEqual(first.output_person_property, second.output_person_property)
+
+ def test_overlong_target_override_raises(self) -> None:
+ with self.assertRaises(ValueError, msg="target_event must be at most 255 characters"):
+ resolve_template(self._make_team(), "feature_adoption", target_event_override="a" * 256)
+
+ def test_long_target_fits_pipeline_columns(self) -> None:
+ result = resolve_template(self._make_team(), "feature_adoption", target_event_override="a" * 250)
+ self.assertLessEqual(len(result.output_person_property), 255)
+ self.assertTrue(result.output_person_property.endswith("_14d"))
+ self.assertLessEqual(len(result.suggested_name), 255)
+
+ @patch(
+ "products.autoresearch.backend.dataset.templates.resolve_activity_event",
+ return_value=("$pageview", ["$screen"]),
+ )
+ def test_activity_alternatives_returned(self, _: MagicMock) -> None:
+ result = resolve_template(self._make_team(), "at_risk_of_inactivity")
+ self.assertIn("$screen", result.activity_event_alternatives)
+
+ @patch("products.autoresearch.backend.dataset.templates.resolve_activity_event", return_value=("$pageview", []))
+ def test_return_after_first_use_population_is_first_seen(self, _: MagicMock) -> None:
+ result = resolve_template(self._make_team(), "return_after_first_use")
+ self.assertEqual(result.training_population, {"kind": "person_first_seen_within_days", "days": 14})