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 template and validation endpoints (14/22) (#89145)

Andrew Maguire57a7816975da
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index 62f25c80a4e2..11352ef636f3 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -105,6 +105,12 @@ def _own_events_excluded_clause(alias: str = "") -> str:
return f" AND {alias}event != '{PREDICTION_EVENT_NAME}'"
+# The most persons one training or scoring run materializes. HogQL otherwise caps a query at its
+# default of 100 rows; the materializers fail a result that fills this bound, and validation
+# refuses a larger population before a run is spent on it.
+MATERIALIZE_ROW_LIMIT = 50_000
+
+
@dataclass(frozen=True, kw_only=True)
class _CompiledPopulationFilters:
# Row-level fragments for an events scan whose ``person`` resolves through the lazy join.
diff --git a/products/autoresearch/backend/dataset/templates.py b/products/autoresearch/backend/dataset/templates.py
index 3a66d560377e..cd9041908e54 100644
--- a/products/autoresearch/backend/dataset/templates.py
+++ b/products/autoresearch/backend/dataset/templates.py
@@ -31,6 +31,8 @@ import re
import hashlib
from typing import Any, Optional
+from django.db import models
+
from posthog.schema import HogQLQuery
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
@@ -38,7 +40,11 @@ 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.dataset.labeling import (
+ LABELER_QUERY_MODIFIERS,
+ _identified_users_and_clause,
+ _own_events_excluded_clause,
+)
from products.autoresearch.backend.query import run_hogql_rows
# Checked in this order when resolving an activity event for universal templates
@@ -51,6 +57,20 @@ _PIPELINE_FIELD_MAX_LENGTH = 255
_UNSAFE_PROPERTY_CHARS = re.compile(r"[^a-z0-9._-]+")
+# Creation's default and the API's cap (`AutoresearchPipelineCreateSerializer.training_lookback_days`).
+# A resolved config carries its own lookback so a long horizon is not created against the default.
+_DEFAULT_TRAINING_LOOKBACK_DAYS = 180
+_MAX_TRAINING_LOOKBACK_DAYS = 730
+
+
+# A TextChoices class because the API's template-key fields and the OpenAPI enum name come from it.
+class TemplateKey(models.TextChoices):
+ LIKELY_ACTIVE_SOON = "likely_active_soon"
+ AT_RISK_OF_INACTIVITY = "at_risk_of_inactivity"
+ RETURN_AFTER_FIRST_USE = "return_after_first_use"
+ FEATURE_ADOPTION = "feature_adoption"
+ REPEAT_KEY_BEHAVIOR = "repeat_key_behavior"
+
@frozen
class AutoresearchTemplate:
@@ -74,8 +94,8 @@ class AutoresearchTemplate:
TEMPLATES: dict[str, AutoresearchTemplate] = {
- "likely_active_soon": AutoresearchTemplate(
- key="likely_active_soon",
+ TemplateKey.LIKELY_ACTIVE_SOON: AutoresearchTemplate(
+ key=TemplateKey.LIKELY_ACTIVE_SOON,
display_name="Likely active soon",
description_template=(
"Predict which active users will be active again in the next {horizon_days} days. "
@@ -92,8 +112,8 @@ TEMPLATES: dict[str, AutoresearchTemplate] = {
"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",
+ TemplateKey.AT_RISK_OF_INACTIVITY: AutoresearchTemplate(
+ key=TemplateKey.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. "
@@ -110,8 +130,8 @@ TEMPLATES: dict[str, AutoresearchTemplate] = {
"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",
+ TemplateKey.RETURN_AFTER_FIRST_USE: AutoresearchTemplate(
+ key=TemplateKey.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. "
@@ -129,8 +149,8 @@ TEMPLATES: dict[str, AutoresearchTemplate] = {
"activity later in the same first session."
),
),
- "feature_adoption": AutoresearchTemplate(
- key="feature_adoption",
+ TemplateKey.FEATURE_ADOPTION: AutoresearchTemplate(
+ key=TemplateKey.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. "
@@ -147,8 +167,8 @@ TEMPLATES: dict[str, AutoresearchTemplate] = {
"within the training lookback window. Use before that window does not exclude a user."
),
),
- "repeat_key_behavior": AutoresearchTemplate(
- key="repeat_key_behavior",
+ TemplateKey.REPEAT_KEY_BEHAVIOR: AutoresearchTemplate(
+ key=TemplateKey.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. "
@@ -199,12 +219,13 @@ def resolve_activity_event(team: Team, user: Optional[User] = None) -> tuple[Opt
SELECT event, uniq(person_id) AS c
FROM events
WHERE timestamp >= now() - toIntervalDay(30)
- AND timestamp < now(){identified_clause}
+ AND timestamp < now(){_own_events_excluded_clause()}{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
""",
+ modifiers=LABELER_QUERY_MODIFIERS,
)
tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
rows = run_hogql_rows(team=team, query=query, user=user)
@@ -240,6 +261,7 @@ class ResolvedTemplate:
resolved_activity_event: Optional[str]
activity_event_alternatives: list[str]
horizon_days: int
+ training_lookback_days: int
training_population: dict[str, Any]
inference_population: dict[str, Any]
output_person_property: str
@@ -247,6 +269,12 @@ class ResolvedTemplate:
notes: str
+def _training_lookback_days(horizon_days: int) -> int:
+ # The labeler places each anchor before now() - horizon, so the horizon eats the recent end
+ # of the lookback. Twice the horizon keeps at least half the window for anchors.
+ return max(_DEFAULT_TRAINING_LOOKBACK_DAYS, min(_MAX_TRAINING_LOOKBACK_DAYS, 2 * horizon_days))
+
+
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.
@@ -346,6 +374,7 @@ def resolve_template(
resolved_activity_event=resolved_activity,
activity_event_alternatives=alternatives,
horizon_days=horizon_days,
+ training_lookback_days=_training_lookback_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),
diff --git a/products/autoresearch/backend/dataset/test_templates.py b/products/autoresearch/backend/dataset/test_templates.py
index 487c1e639f0b..a6b25b02fb4e 100644
--- a/products/autoresearch/backend/dataset/test_templates.py
+++ b/products/autoresearch/backend/dataset/test_templates.py
@@ -4,10 +4,15 @@ 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.labeling import (
+ LABELER_QUERY_MODIFIERS,
+ PREDICTION_EVENT_NAME,
+ _build_population_kind_conditions,
+)
from products.autoresearch.backend.dataset.templates import (
TEMPLATES,
ResolvedTemplate,
+ TemplateKey,
resolve_activity_event,
resolve_template,
)
@@ -25,6 +30,8 @@ class TestTemplateDefinitions(SimpleTestCase):
"repeat_key_behavior",
},
)
+ # Every key the API advertises resolves, and every template is reachable through the API.
+ self.assertEqual(set(TemplateKey.values), set(TEMPLATES))
@parameterized.expand(list(TEMPLATES.keys()))
def test_template_has_required_fields(self, key: str) -> None:
@@ -86,9 +93,11 @@ class TestResolveActivityEvent(SimpleTestCase):
) 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)
+ query = mock_run.call_args.kwargs["query"]
+ self.assertIn("person.is_identified", query.query)
+ self.assertIn("uniq(person_id)", query.query)
+ self.assertIn(f"event != '{PREDICTION_EVENT_NAME}'", query.query)
+ self.assertEqual(query.modifiers, LABELER_QUERY_MODIFIERS)
self.assertIs(mock_run.call_args.kwargs["user"], user)
@parameterized.expand(
@@ -190,6 +199,12 @@ class TestResolveTemplate(SimpleTestCase):
self.assertEqual(result.training_population, {"kind": "ever_performed_target"})
self.assertIn("pageview", result.output_person_property)
+ @parameterized.expand([("default", 7, 180), ("long", 100, 200), ("longest", 365, 730)])
+ def test_training_lookback_grows_with_the_horizon(self, _name: str, horizon: int, lookback: int) -> None:
+ result = resolve_template(self._make_team(), "feature_adoption", "signed_up", horizon_days_override=horizon)
+ self.assertEqual(result.training_lookback_days, lookback)
+ self.assertGreater(result.training_lookback_days, result.horizon_days)
+
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)
diff --git a/products/autoresearch/backend/dataset/test_validation.py b/products/autoresearch/backend/dataset/test_validation.py
index dc1d730c8b67..6fc12b667173 100644
--- a/products/autoresearch/backend/dataset/test_validation.py
+++ b/products/autoresearch/backend/dataset/test_validation.py
@@ -3,6 +3,9 @@ from unittest.mock import patch
from parameterized import parameterized
+from posthog.hogql.errors import QueryError
+
+from products.autoresearch.backend.dataset.labeling import LABELER_QUERY_MODIFIERS, PREDICTION_EVENT_NAME
from products.autoresearch.backend.dataset.validation import (
ValidationResult,
_run_validation,
@@ -54,6 +57,7 @@ class TestValidationWarnings(BaseTest):
("zero_users", 0, 0, "low_volume"),
("low_positives", 5, 1000, "low_positives"),
("low_negatives", 995, 1000, "low_negatives"),
+ ("population_too_large", 5_000, 50_000, "population_too_large"),
]
)
def test_hard_errors_block_proceeding(self, _name: str, positives: int, total: int, code: str) -> None:
@@ -92,9 +96,19 @@ class TestValidationWarnings(BaseTest):
codes = [w.code for w in result.warnings]
assert "mostly_anonymous_population" not in codes
- def test_error_in_query_returns_error_result(self) -> None:
+ @parameterized.expand(
+ [
+ (
+ "infrastructure_detail_stays_in_the_log",
+ RuntimeError("CH is down at 10.0.0.1"),
+ "Validation could not run",
+ ),
+ ("query_error_reaches_the_caller", QueryError("Field not found: nope"), "Field not found: nope"),
+ ]
+ )
+ def test_error_in_query_returns_error_result(self, _name: str, exc: Exception, expected: str) -> None:
with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
- mock_run.side_effect = RuntimeError("CH is down")
+ mock_run.side_effect = exc
result = validate_pipeline_definition(
team=self.team,
target_event="$pageview",
@@ -105,14 +119,44 @@ class TestValidationWarnings(BaseTest):
)
assert result.can_proceed is False
assert result.error is not None
- assert "CH is down" in result.error
+ assert expected in result.error
+ assert "10.0.0.1" not in result.error
+
+ def test_horizon_at_or_past_the_lookback_is_refused_before_any_query(self) -> None:
+ with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
+ result = _run_validation(
+ team=self.team,
+ target_event="$pageview",
+ horizon_days=180,
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ )
+ assert mock_run.call_count == 0
+ assert result.can_proceed is False
+ assert [w.code for w in result.warnings] == ["horizon_exceeds_lookback"]
+
+ def test_count_queries_use_the_labeler_join_mode_and_skip_own_events(self) -> None:
+ with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
+ mock_run.side_effect = _mock_rows(100, 1000)
+ _run_validation(
+ team=self.team,
+ target_event="$pageview",
+ horizon_days=7,
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ )
+ queries = [call.kwargs["query"] for call in mock_run.call_args_list]
+ assert [q.modifiers for q in queries] == [LABELER_QUERY_MODIFIERS] * 3
+ assert all(f"event != '{PREDICTION_EVENT_NAME}'" in q.query for q in queries)
@parameterized.expand([("short_horizon_floors_at_30", 7, 30), ("long_horizon_is_4x", 14, 56)])
- def test_inference_preview_uses_scoring_lookback(
+ def test_inference_preview_matches_the_scoring_window(
self, _name: str, horizon_days: int, expected_lookback: int
) -> None:
- # Scoring anchors on max(30, 4 * horizon); previewing over the 180-day training
- # lookback overstates the population that will actually be scored.
+ # Scoring anchors on max(30, 4 * horizon) at the UTC midnight of the prediction date;
+ # previewing over the training lookback at now() would count a different population.
with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
mock_run.side_effect = _mock_rows(100, 1000)
_run_validation(
@@ -125,6 +169,7 @@ class TestValidationWarnings(BaseTest):
)
inference_query = mock_run.call_args_list[2].kwargs["query"]
assert inference_query.values["lookback"] == expected_lookback
+ assert inference_query.values["cutoff_ts"] % 86400 == 0
def test_training_window_is_the_configured_lookback(self) -> None:
with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
diff --git a/products/autoresearch/backend/dataset/validation.py b/products/autoresearch/backend/dataset/validation.py
index 0f448a8a207c..2371e854e7b3 100644
--- a/products/autoresearch/backend/dataset/validation.py
+++ b/products/autoresearch/backend/dataset/validation.py
@@ -1,22 +1,26 @@
from dataclasses import field
+from datetime import UTC, datetime, time
+from enum import StrEnum
from typing import Any, Optional
import structlog
from posthog.schema import HogQLQuery
+from posthog.hogql.errors import ExposedHogQLError
+
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.dataclasses import frozen
+from posthog.errors import ExposedCHQueryError
from posthog.models.team.team import Team
from posthog.models.user import User
from products.autoresearch.backend.dataset.labeling import (
IDENTIFIED_USERS_ONLY,
- _build_population_conditions,
- _build_population_kind_conditions,
- _identified_users_and_clause,
- _target_condition_for,
+ LABELER_QUERY_MODIFIERS,
+ MATERIALIZE_ROW_LIMIT,
build_eligible_count_sql,
+ build_inference_anchors_sql,
build_random_t0_labeler_sql,
)
from products.autoresearch.backend.query import run_hogql_rows
@@ -44,6 +48,34 @@ def inference_lookback_days(horizon_days: int) -> int:
return max(30, horizon_days * 4)
+def _scoring_cutoff_ts() -> int:
+ # The start of today in UTC, which is the instant a live run for today binds (`ScoringWindow.for_date`).
+ return int(datetime.combine(datetime.now(UTC).date(), time.min, tzinfo=UTC).timestamp())
+
+
+# The API's help text lists the same codes, and a test holds the two together.
+class ValidationWarningCode(StrEnum):
+ LOW_VOLUME = "low_volume"
+ MODERATE_VOLUME = "moderate_volume"
+ MOSTLY_ANONYMOUS_POPULATION = "mostly_anonymous_population"
+ LOW_POSITIVES = "low_positives"
+ LOW_NEGATIVES = "low_negatives"
+ EXTREME_IMBALANCE = "extreme_imbalance"
+ NEAR_UNIVERSAL = "near_universal"
+ POPULATION_TOO_LARGE = "population_too_large"
+ HORIZON_EXCEEDS_LOOKBACK = "horizon_exceeds_lookback"
+
+
+_GENERIC_ERROR = "Validation could not run. Try again, and contact support if it keeps failing."
+
+
+def _exposed_error(exc: Exception) -> str:
+ # Exposed errors describe the caller's own definition, so anything else is our infrastructure and stays in the log.
+ if isinstance(exc, ExposedHogQLError | ExposedCHQueryError):
+ return str(exc)
+ return _GENERIC_ERROR
+
+
@frozen
class ValidationWarning:
code: str
@@ -103,7 +135,7 @@ def validate_pipeline_definition(
negative_count=None,
base_rate=None,
inference_population_size=None,
- error=str(exc),
+ error=_exposed_error(exc),
)
@@ -118,6 +150,27 @@ def _run_validation(
target_definition: dict[str, Any] | None = None,
user: User | None = None,
) -> ValidationResult:
+ if horizon_days >= training_lookback_days:
+ # No anchor can fall before now() - horizon inside this lookback, so refuse before spending three queries.
+ return ValidationResult(
+ can_proceed=False,
+ requires_acknowledgement=False,
+ estimated_training_rows=0,
+ positive_count=0,
+ negative_count=0,
+ base_rate=0.0,
+ inference_population_size=None,
+ warnings=[
+ ValidationWarning(
+ code=ValidationWarningCode.HORIZON_EXCEEDS_LOOKBACK,
+ message=f"A {horizon_days}-day horizon needs a training lookback longer than {horizon_days} days, "
+ f"and this one is {training_lookback_days}. Training would find no examples. "
+ "Raise training_lookback_days or shorten the horizon.",
+ severity="error",
+ )
+ ],
+ )
+
tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
# Headline eligible count — true number of users that would be labeled by the
@@ -131,7 +184,11 @@ def _run_validation(
target_definition=target_definition,
team=team,
)
- eligible_rows = run_hogql_rows(team=team, query=HogQLQuery(query=eligible_sql, values=eligible_values), user=user)
+ eligible_rows = run_hogql_rows(
+ team=team,
+ query=HogQLQuery(query=eligible_sql, values=eligible_values, modifiers=LABELER_QUERY_MODIFIERS),
+ user=user,
+ )
# eligible = identified-only headline (v1); eligible_all = same count without the
# identified restriction, used to detect a mostly-anonymous population.
total_users = 0
@@ -154,7 +211,11 @@ def _run_validation(
training_population=training_population,
sample_limit=LIVE_ESTIMATE_SAMPLE_LIMIT,
)
- label_rows = run_hogql_rows(team=team, query=HogQLQuery(query=label_sql, values=label_values), user=user)
+ label_rows = run_hogql_rows(
+ team=team,
+ query=HogQLQuery(query=label_sql, values=label_values, modifiers=LABELER_QUERY_MODIFIERS),
+ user=user,
+ )
sampled_users = 0
sampled_positives = 0
if label_rows:
@@ -167,30 +228,19 @@ def _run_validation(
positives = round(base_rate * total_users) if total_users > 0 else 0
negatives = total_users - positives
- # Inference population: distinct users matching the prediction filter over the
- # window the scorer binds. Always counted, even with no filter, so the preview
- # stays aligned with what `build_inference_anchors_sql` scores.
- inference_properties = (inference_population or {}).get("properties", []) if inference_population else []
- # Template populations carry a `kind` rather than raw properties, so compile it through
- # the same helper scoring uses — counting every identified user would preview a
- # population the pipeline will never score.
- target_cond, target_values = _target_condition_for(
- inference_population, target_event=target_event, target_definition=target_definition, team=team
+ # Count the scorer's own anchor query at today's cutoff, so the preview cannot drift from what gets scored.
+ anchors_sql, anchors_values = build_inference_anchors_sql(
+ lookback_days=inference_lookback_days(horizon_days),
+ inference_population=inference_population,
+ cutoff_ts=_scoring_cutoff_ts(),
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
)
- compiled_inference_kind = _build_population_kind_conditions(inference_population, target_cond=target_cond)
- inf_parts, inf_values = _build_population_conditions(inference_properties)
- inf_parts.extend(compiled_inference_kind.where_parts)
- inf_values.update(target_values)
- inf_values.update(compiled_inference_kind.values)
- inference_clause = f" AND ({' AND '.join(inf_parts)})" if inf_parts else ""
inference_query = HogQLQuery(
- query=f"""
- SELECT countDistinct(person_id) AS users
- FROM events
- WHERE timestamp >= now() - toIntervalDay({{lookback}})
- AND timestamp < now(){inference_clause}{_identified_users_and_clause()}
- """,
- values={"lookback": inference_lookback_days(horizon_days), **inf_values},
+ query=f"SELECT count() FROM ({anchors_sql.strip()})",
+ values=anchors_values,
+ modifiers=LABELER_QUERY_MODIFIERS,
)
inf_rows = run_hogql_rows(team=team, query=inference_query, user=user)
inference_size = int(inf_rows[0][0] or 0) if inf_rows else 0
@@ -203,6 +253,7 @@ def _run_validation(
base_rate=base_rate,
lookback_days=training_lookback_days,
target_event=target_event,
+ inference_size=inference_size,
)
has_errors = any(w.severity == "error" for w in warnings)
has_hard_warnings = any(w.severity == "warning" for w in warnings)
@@ -228,6 +279,7 @@ def _build_warnings(
base_rate: float,
lookback_days: int,
target_event: str,
+ inference_size: int,
) -> list[ValidationWarning]:
warnings: list[ValidationWarning] = []
@@ -235,7 +287,7 @@ def _build_warnings(
if total_users < MIN_TRAINING_ROWS:
warnings.append(
ValidationWarning(
- code="low_volume",
+ code=ValidationWarningCode.LOW_VOLUME,
message=f"Only {total_users} users found in the last {lookback_days} days. "
f"At least {MIN_TRAINING_ROWS} are recommended for reliable training.",
severity="error",
@@ -244,7 +296,7 @@ def _build_warnings(
elif total_users < MIN_TRAINING_ROWS * 5:
warnings.append(
ValidationWarning(
- code="moderate_volume",
+ code=ValidationWarningCode.MODERATE_VOLUME,
message=f"{total_users} users found. The model may have limited accuracy with this volume.",
severity="warning",
)
@@ -259,7 +311,7 @@ def _build_warnings(
excluded = total_users_all - total_users
warnings.append(
ValidationWarning(
- code="mostly_anonymous_population",
+ code=ValidationWarningCode.MOSTLY_ANONYMOUS_POPULATION,
message=f"Only {identified_fraction:.0%} of this population is identified. "
f"Autoresearch models identified users only, so {excluded} anonymous "
f"user(s) are excluded from training and scoring.",
@@ -270,7 +322,7 @@ def _build_warnings(
if positives < MIN_POSITIVE_EXAMPLES:
warnings.append(
ValidationWarning(
- code="low_positives",
+ code=ValidationWarningCode.LOW_POSITIVES,
message=f"Only {positives} users performed '{target_event}'. "
f"At least {MIN_POSITIVE_EXAMPLES} positive examples are needed.",
severity="error",
@@ -280,7 +332,7 @@ def _build_warnings(
if negatives < MIN_NEGATIVE_EXAMPLES:
warnings.append(
ValidationWarning(
- code="low_negatives",
+ code=ValidationWarningCode.LOW_NEGATIVES,
message=f"Only {negatives} users did not perform '{target_event}'. "
f"At least {MIN_NEGATIVE_EXAMPLES} negative examples are needed.",
severity="error",
@@ -291,7 +343,7 @@ def _build_warnings(
if total_users > 0 and base_rate < 0.01:
warnings.append(
ValidationWarning(
- code="extreme_imbalance",
+ code=ValidationWarningCode.EXTREME_IMBALANCE,
message=f"Base rate is {base_rate:.2%}. Very rare events need a larger population "
"for reliable calibration.",
severity="warning",
@@ -300,11 +352,22 @@ def _build_warnings(
elif total_users > 0 and base_rate > 0.95:
warnings.append(
ValidationWarning(
- code="near_universal",
+ code=ValidationWarningCode.NEAR_UNIVERSAL,
message=f"Base rate is {base_rate:.2%}. Almost everyone does this event, "
"so the model may not add much predictive value.",
severity="warning",
)
)
+ largest = max(total_users, inference_size)
+ if largest >= MATERIALIZE_ROW_LIMIT:
+ warnings.append(
+ ValidationWarning(
+ code=ValidationWarningCode.POPULATION_TOO_LARGE,
+ message=f"This population has {largest} users. One run trains or scores at most "
+ f"{MATERIALIZE_ROW_LIMIT} users. Narrow the population.",
+ severity="error",
+ )
+ )
+
return warnings
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 31545d666490..c075666d7bf5 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -12,14 +12,33 @@ filters on it. Business rules live in the modules behind this facade, not in the
from typing import Any
from uuid import UUID
+from posthog.models.team import Team
+from posthog.models.user import User
+
from products.actions.backend.models.action import Action
+from ..dataset import templates as templates_module
from ..dataset.labeling import (
POPULATION_KINDS as _POPULATION_KINDS,
PREDICTION_EVENT_NAME as _PREDICTION_EVENT_NAME,
)
+from ..dataset.templates import TemplateKey as _TemplateKey
+from ..dataset.validation import (
+ ValidationWarningCode as _ValidationWarningCode,
+ validate_pipeline_definition as _validate_pipeline_definition,
+)
from ..models import AutoresearchModel, AutoresearchPipeline
-from .contracts import InvalidTarget, Pipeline, PipelineNotFound, PipelineWrite
+from .contracts import (
+ AutoresearchConflict,
+ InvalidTarget,
+ Pipeline,
+ PipelineNotFound,
+ PipelineValidation,
+ PipelineWrite,
+ ResolvedTemplate,
+ TemplateInfo,
+ ValidationWarning,
+)
AUTORESEARCH_FLAG = "autoresearch"
@@ -205,6 +224,95 @@ def resolve_action_target(project_id: int, action_id: Any) -> tuple[str, int]:
return action.name or "", int(action_id)
+# ── Validation and templates ───────────────────────────────────────────────
+
+
+def list_templates() -> list[TemplateInfo]:
+ return [
+ TemplateInfo(
+ key=t.key,
+ display_name=t.display_name,
+ description=t.description,
+ default_horizon_days=t.default_horizon_days,
+ requires_user_event=t.requires_user_event,
+ requires_activity_resolution=t.requires_activity_resolution,
+ notes=t.notes,
+ )
+ for t in templates_module.TEMPLATES.values()
+ ]
+
+
+def resolve_template(
+ team_id: int,
+ *,
+ template_key: str,
+ target_event_override: str | None = None,
+ horizon_days_override: int | None = None,
+ user: User,
+) -> ResolvedTemplate:
+ team = Team.objects.get(pk=team_id)
+ try:
+ resolved = templates_module.resolve_template(
+ team=team,
+ template_key=template_key,
+ target_event_override=target_event_override,
+ horizon_days_override=horizon_days_override,
+ user=user,
+ )
+ except ValueError as exc:
+ raise AutoresearchConflict(str(exc)) from exc
+ return ResolvedTemplate(
+ template_key=resolved.template_key,
+ display_name=resolved.display_name,
+ description=resolved.description,
+ suggested_name=resolved.suggested_name,
+ target_event=resolved.target_event,
+ resolved_activity_event=resolved.resolved_activity_event,
+ activity_event_alternatives=list(resolved.activity_event_alternatives),
+ horizon_days=resolved.horizon_days,
+ training_lookback_days=resolved.training_lookback_days,
+ training_population=resolved.training_population,
+ inference_population=resolved.inference_population,
+ output_person_property=resolved.output_person_property,
+ notes=resolved.notes,
+ )
+
+
+def validate_definition(
+ team_id: int,
+ *,
+ target_event: str,
+ target_definition: dict[str, Any],
+ horizon_days: int,
+ training_lookback_days: int,
+ training_population: dict[str, Any],
+ inference_population: dict[str, Any],
+ user: User,
+) -> PipelineValidation:
+ team = Team.objects.get(pk=team_id)
+ result = _validate_pipeline_definition(
+ team=team,
+ target_event=target_event,
+ target_definition=target_definition,
+ horizon_days=horizon_days,
+ training_lookback_days=training_lookback_days,
+ training_population=training_population,
+ inference_population=inference_population,
+ user=user,
+ )
+ return PipelineValidation(
+ can_proceed=result.can_proceed,
+ requires_acknowledgement=result.requires_acknowledgement,
+ estimated_training_rows=result.estimated_training_rows,
+ positive_count=result.positive_count,
+ negative_count=result.negative_count,
+ base_rate=result.base_rate,
+ inference_population_size=result.inference_population_size,
+ warnings=[ValidationWarning(code=w.code, message=w.message, severity=w.severity) for w in result.warnings],
+ error=result.error,
+ )
+
+
# ── Recipe validation surface for the presentation layer ───────────────────
# The semantic population kinds the labeler can compile. Presentation validates a submitted
@@ -223,3 +331,6 @@ PREDICTION_EVENT_NAME = _PREDICTION_EVENT_NAME
# model-bound serializers produced — including the one shared with another product, which
# `ENUM_NAME_OVERRIDES` pins by value set.
PIPELINE_STATUS_CHOICES = AutoresearchPipeline.Status.choices
+TEMPLATE_KEY_CHOICES = _TemplateKey.choices
+# A plain list, not choices: the serializer explains why `code` is not an enum.
+VALIDATION_WARNING_CODES = [code.value for code in _ValidationWarningCode]
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 49861530fed1..c0bf52889503 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -106,3 +106,56 @@ class PipelineWrite:
success_auc: float | None = None
plateau_iterations: int = 10
output_person_property: str = ""
+
+
+# ── Validation and template contracts ──────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class ValidationWarning:
+ code: str
+ message: str
+ severity: str
+
+
+@dataclass(frozen=True)
+class PipelineValidation:
+ """Volume, base rate, and warnings for a proposed pipeline definition."""
+
+ can_proceed: bool
+ requires_acknowledgement: bool
+ estimated_training_rows: int | None
+ positive_count: int | None
+ negative_count: int | None
+ base_rate: float | None
+ inference_population_size: int | None
+ warnings: list[ValidationWarning]
+ error: str | None
+
+
+@dataclass(frozen=True)
+class TemplateInfo:
+ key: str
+ display_name: str
+ description: str
+ default_horizon_days: int
+ requires_user_event: bool
+ requires_activity_resolution: bool
+ notes: str
+
+
+@dataclass(frozen=True)
+class ResolvedTemplate:
+ template_key: str
+ display_name: str
+ description: str
+ suggested_name: str
+ target_event: str
+ resolved_activity_event: str | None
+ activity_event_alternatives: list[str]
+ horizon_days: int
+ training_lookback_days: int
+ training_population: dict[str, Any]
+ inference_population: dict[str, Any]
+ output_person_property: str
+ notes: str
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index d4adcaf24910..ba126fc92de1 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -63,6 +63,7 @@ from posthog.models.user import User
from products.autoresearch.backend.dataset.labeling import (
LABELER_QUERY_MODIFIERS,
+ MATERIALIZE_ROW_LIMIT,
build_inference_anchors_sql,
build_inference_features_sql,
build_random_t0_labeler_sql,
@@ -112,10 +113,7 @@ _PREDICT_TIMEOUT_S = 120
# A sandbox that outlives its command is a worker that died mid-run. The TTL is the
# backstop that reclaims it: long enough for uploads, the command, and readback.
_SANDBOX_TTL_S = 20 * 60
-# Without an explicit bound HogQL caps a query at its default of 100 rows, which would
-# shrink the train, holdout, and score matrices to a tiny sample. scoring.py bounds its
-# queries with the same constant.
-_MATERIALIZE_ROW_LIMIT = 50_000
+_MATERIALIZE_ROW_LIMIT = MATERIALIZE_ROW_LIMIT
_OUTPUT_JSON = "data/output.json"
_SCORES_PARQUET = "data/scores.parquet"
_SCRIPT_LOG = "data/script.log"
diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.md
index 47efe945cfff..6c4b25c28cb5 100644
--- a/products/autoresearch/backend/presentation/AGENTS.md
+++ b/products/autoresearch/backend/presentation/AGENTS.md
@@ -5,14 +5,14 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably m
These serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.
A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.
-This package lands one endpoint group at a time. Pipeline CRUD is here; the pre-create helpers, the lifecycle actions, the read-only model and run viewsets, the training-run agent surface, and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.
+This package lands one endpoint group at a time. Pipeline CRUD and the pre-create helpers are here; the lifecycle actions, the read-only model and run viewsets, the training-run agent surface, and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.
## What lives here
-- `views.py`
+- `views/views.py`
One viewset so far, registered in `../routes.py` under the `project_autoresearch_pipelines` basename.
- - `AutoresearchPipelineViewSet` — full CRUD.
-- `serializers.py`
+ - `AutoresearchPipelineViewSet` — full CRUD plus the pre-create helpers `templates`, `resolve-template`, `validate`.
+- `views/serializers.py`
Request and response shapes, plus `resolve_target()`, which turns a pipeline's `target_event` or `target_definition` (an action reference) into the resolved target the rest of the product uses.
It refuses the product's own `autoresearch_prediction` event, and an action with a step that can match it, because the labeler and online validation exclude that event from every scan.
@@ -27,7 +27,7 @@ Every viewset sets `scope_object = "autoresearch"` and splits `scope_object_read
- **Routing** — `../routes.py` (`register_routes`).
- **Frontend types** — generated into `../../frontend/generated/` via drf-spectacular + Orval. Never hand-edit those; change the serializer and regenerate with `hogli build:openapi`.
-- **Calls into** — `../dataset/` (`resolve_target`).
+- **Calls into** — `../dataset/` (validate, templates, `resolve_target`).
## Declare the response when it differs from the request
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 98730fd1fabb..b6c80e8d2eb7 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -5,9 +5,11 @@ from typing import Any
from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from rest_framework.fields import empty
+from rest_framework.request import Request
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.shared import UserBasicSerializer
+from posthog.permissions import get_authenticator_scopes
from products.autoresearch.backend.facade import api
from products.autoresearch.backend.facade.contracts import Pipeline, PipelineWrite
@@ -17,6 +19,8 @@ POPULATION_KINDS = api.POPULATION_KINDS
# (value, label) pairs, not bare values: drf-spectacular builds each enum component's name and
# its label list from them, and `ENUM_NAME_OVERRIDES` matches on the value set.
PIPELINE_STATUS_CHOICES = api.PIPELINE_STATUS_CHOICES
+TEMPLATE_KEY_CHOICES = api.TEMPLATE_KEY_CHOICES
+VALIDATION_WARNING_CODES = api.VALIDATION_WARNING_CODES
TARGET_EVENT_MAX_LENGTH = 255
OUTPUT_PERSON_PROPERTY_MAX_LENGTH = 255
@@ -28,6 +32,9 @@ _FORBIDDEN_TARGET_EVENT_CHARS = re.compile(r"[\x00-\x1f\x7f`{}]")
_OUTPUT_PERSON_PROPERTY_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_$.\-]*$")
+# Resolving an action target reveals whether the id exists and its name, so a scoped token needs a read scope.
+_ACTION_READ_SCOPES = ("action:read", "action:write", "*")
+
def _validate_target_event_value(value: str, *, error_key: str) -> None:
if len(value) > TARGET_EVENT_MAX_LENGTH:
@@ -40,11 +47,28 @@ def _validate_target_event_value(value: str, *, error_key: str) -> None:
)
+def validate_event_target(target_event: str, *, error_key: str) -> None:
+ """The rules creation applies to an event target: not the product's own event, and safe to place in
+ the training agent's prompt brief. Template resolution applies them so its result is one creation accepts."""
+ if target_event == api.PREDICTION_EVENT_NAME:
+ raise serializers.ValidationError(
+ {error_key: f"'{api.PREDICTION_EVENT_NAME}' is the event this product emits, so it cannot be a target."}
+ )
+ _validate_target_event_value(target_event, error_key=error_key)
+
+
+def _require_action_scope(request: Request | None) -> None:
+ scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if scopes is not None and not any(scope in scopes for scope in _ACTION_READ_SCOPES):
+ raise serializers.ValidationError({"target_definition": "An action target needs the action:read scope."})
+
+
def resolve_target(
*,
team: Any,
target_event: str,
target_definition: dict[str, Any] | None,
+ request: Request | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Validate and normalize a prediction target, returning (target_event, target_definition).
@@ -77,6 +101,7 @@ def resolve_target(
raise serializers.ValidationError(
{"target_definition": "Action target requires a positive integer 'action_id'."}
)
+ _require_action_scope(request)
try:
action_name, action_id = api.resolve_action_target(team.project_id, action_id)
except (api.PipelineNotFound, api.InvalidTarget) as exc:
@@ -98,13 +123,7 @@ def resolve_target(
)
}
)
- if target_event == api.PREDICTION_EVENT_NAME:
- raise serializers.ValidationError(
- {
- "target_event": f"'{api.PREDICTION_EVENT_NAME}' is the event this product emits, so it cannot be a target."
- }
- )
- _validate_target_event_value(target_event, error_key="target_event")
+ validate_event_target(target_event, error_key="target_event")
return target_event, {"type": "event"}
@@ -163,6 +182,9 @@ _POPULATION_KIND_REQUIRED_DAYS: dict[str, str | None] = {
}
_POPULATION_KIND_REQUIRES_EVENT = frozenset({"ever_performed_event"})
_POPULATION_DAYS_MAX = 730
+# Every filter and list-valued operand becomes a bound parameter in several HogQL queries, so bound the body first.
+_POPULATION_FILTERS_MAX = 20
+_POPULATION_FILTER_VALUES_MAX = 200
@extend_schema_field(
@@ -193,6 +215,16 @@ class PopulationDefinitionField(serializers.JSONField):
not isinstance(properties, list) or any(not isinstance(p, dict) for p in properties)
):
raise serializers.ValidationError("Population 'properties' must be a list of filter objects.")
+ if properties and len(properties) > _POPULATION_FILTERS_MAX:
+ raise serializers.ValidationError(
+ f"A population can have at most {_POPULATION_FILTERS_MAX} property filters."
+ )
+ for prop in properties or []:
+ operand = prop.get("value")
+ if isinstance(operand, list) and len(operand) > _POPULATION_FILTER_VALUES_MAX:
+ raise serializers.ValidationError(
+ f"A property filter can list at most {_POPULATION_FILTER_VALUES_MAX} values."
+ )
kind = value.get("kind")
if kind is None:
return value
@@ -525,6 +557,7 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
team=team,
target_event=self._value(data, "target_event", ""),
target_definition=self._value(data, "target_definition"),
+ request=self.context.get("request"),
)
updates["target_event"] = target_event
updates["target_definition"] = target_definition
@@ -548,3 +581,233 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
if not is_update and not self._value(data, "inference_population"):
updates["inference_population"] = self._value(data, "training_population", {})
return replace(data, **updates) if updates else data
+
+
+# ── Validation serializers -------------------------------------------------
+
+
+class ValidationWarningSerializer(serializers.Serializer):
+ # A CharField on purpose: a ChoiceField named `code` collides with another product's `code` enum in drf-spectacular.
+ code = serializers.CharField(
+ help_text=(
+ "Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a "
+ "training run would fail: fix the definition before creating. 'low_volume', 'low_positives' and "
+ "'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). "
+ "'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are "
+ "severity 'warning'."
+ ),
+ )
+ message = serializers.CharField(help_text="Human-readable warning description.")
+ severity = serializers.ChoiceField(
+ choices=["info", "warning", "error"],
+ help_text=(
+ "Severity level. 'error' means training would fail or the data is too thin for a reliable model; "
+ "see 'code' for which. 'warning' is worth acknowledging. Creation enforces none of them."
+ ),
+ )
+
+
+class ValidatePipelineRequestSerializer(serializers.Serializer):
+ target_event = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text=(
+ "Event name to predict, e.g. '$pageview'. Must exist in the team's event schema. "
+ "Omit when predicting an action target (pass target_definition instead)."
+ ),
+ )
+ target_definition = TargetDefinitionField(
+ required=False,
+ default=dict,
+ help_text=(
+ 'Optional target definition. Pass {"type": "action", "action_id": N} to predict a '
+ "PostHog action (multi-step / property / autocapture matcher) instead of a single event."
+ ),
+ )
+ horizon_days = serializers.IntegerField(
+ default=7,
+ min_value=1,
+ max_value=365,
+ help_text="Predict whether the target event occurs within this many days.",
+ )
+ training_lookback_days = serializers.IntegerField(
+ default=180,
+ min_value=7,
+ max_value=730,
+ help_text="How far back to look for training examples. Default: 180.",
+ )
+ training_population = PopulationDefinitionField(
+ default=dict,
+ help_text="Population filter for training examples. Use {} for all identified users.",
+ )
+ inference_population = PopulationDefinitionField(
+ default=dict,
+ help_text=(
+ "Population filter for daily scoring. When omitted or empty, the training population is "
+ "counted, as creation stores it."
+ ),
+ )
+
+
+class ValidatePipelineResponseSerializer(serializers.Serializer):
+ can_proceed = serializers.BooleanField(
+ help_text=(
+ "False when any warning has severity 'error'. Creation does not enforce it, but a definition with "
+ "'population_too_large' or 'horizon_exceeds_lookback' cannot train."
+ )
+ )
+ requires_acknowledgement = serializers.BooleanField(
+ help_text="True if there are non-blocking warnings the user should acknowledge before proceeding."
+ )
+ estimated_training_rows = serializers.IntegerField(
+ allow_null=True,
+ help_text="Estimated number of user-level training rows based on the population and lookback window.",
+ )
+ positive_count = serializers.IntegerField(
+ allow_null=True,
+ help_text="Estimated number of positive examples (users who performed the target event).",
+ )
+ negative_count = serializers.IntegerField(allow_null=True, help_text="Estimated number of negative examples.")
+ base_rate = serializers.FloatField(
+ allow_null=True,
+ help_text="Fraction of the training population that performed the target event.",
+ )
+ inference_population_size = serializers.IntegerField(
+ allow_null=True,
+ help_text="Estimated number of users in the inference (daily scoring) population.",
+ )
+ warnings = ValidationWarningSerializer(
+ many=True, help_text="List of validation warnings. Check 'severity' and 'code'."
+ )
+ error = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Why validation did not run, or null when it did. A query error in the definition itself "
+ "is passed through; any other failure is a generic message and the detail is logged."
+ ),
+ )
+
+
+# ── Template serializers ───────────────────────────────────────────────────────
+
+
+class TemplateInfoSerializer(serializers.Serializer):
+ key = serializers.ChoiceField(
+ choices=TEMPLATE_KEY_CHOICES,
+ help_text="Template identifier, e.g. 'likely_active_soon'. Pass to autoresearch-resolve-template-create.",
+ )
+ display_name = serializers.CharField(help_text="Human-readable template name.")
+ description = serializers.CharField(help_text="What this template predicts and who it is for.")
+ default_horizon_days = serializers.IntegerField(
+ help_text="Default prediction horizon in days. Can be overridden when resolving.",
+ )
+ requires_user_event = serializers.BooleanField(
+ help_text=(
+ "If true, you must supply a target_event when resolving — the template does not auto-select one. "
+ "Required for 'feature_adoption' and 'repeat_key_behavior'."
+ ),
+ )
+ requires_activity_resolution = serializers.BooleanField(
+ help_text=(
+ "If true, the target event is automatically resolved from your event schema "
+ "($pageview, $screen, or the highest-volume non-noisy event). "
+ "You can override the resolved event when resolving the template."
+ ),
+ )
+ notes = serializers.CharField(help_text="Usage guidance and implementation notes.")
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "description": (
+ "Semantic population filter compiled to HogQL by the training/inference harness. "
+ "Supported kinds: 'performed_event_within_days' (users who did event in last N days), "
+ "'person_first_seen_within_days' (new users by first-seen date), "
+ "'active_not_performed_target' (active users who have NOT done the target event), "
+ "'ever_performed_event' (users who have done the target event at least once)."
+ ),
+ "example": {"kind": "performed_event_within_days", "event": "$pageview", "days": 30},
+ }
+)
+class PopulationSpecField(serializers.JSONField):
+ pass
+
+
+class ResolveTemplateRequestSerializer(serializers.Serializer):
+ template_key = serializers.ChoiceField(
+ choices=TEMPLATE_KEY_CHOICES,
+ help_text=(
+ "Template to resolve. Use autoresearch-templates-list to see all available templates "
+ "with descriptions. Required."
+ ),
+ )
+ target_event = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ help_text=(
+ "Event name to use as the prediction target. "
+ "Required for 'feature_adoption' and 'repeat_key_behavior'. "
+ "Optional override for activity-based templates ('likely_active_soon', "
+ "'at_risk_of_inactivity', 'return_after_first_use'); omit to use the auto-resolved event. "
+ "To predict an action, create the pipeline with target_definition after resolving."
+ ),
+ )
+ horizon_days = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=365,
+ help_text="Override the template's default prediction horizon in days.",
+ )
+
+
+class ResolvedTemplateSerializer(serializers.Serializer):
+ template_key = serializers.ChoiceField(
+ choices=TEMPLATE_KEY_CHOICES,
+ help_text="The template key that was resolved. Pass it back to re-resolve with a different target_event.",
+ )
+ display_name = serializers.CharField(help_text="Human-readable template name.")
+ description = serializers.CharField(help_text="What this template predicts.")
+ suggested_name = serializers.CharField(help_text="Suggested pipeline name. Pass as 'name' to autoresearch-create.")
+ target_event = serializers.CharField(
+ help_text=(
+ "Resolved target event. Pass as 'target_event' to autoresearch-create. "
+ "For activity-based templates this is the auto-resolved activity event (or your override)."
+ ),
+ )
+ resolved_activity_event = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Activity event found in your event schema, populated only for templates that "
+ "auto-resolve the target ('likely_active_soon', 'at_risk_of_inactivity', "
+ "'return_after_first_use'). Null for templates where you supply target_event directly."
+ ),
+ )
+ activity_event_alternatives = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "Other viable activity events found in your schema. "
+ "If the resolved event is not the right signal, re-resolve with one of these as target_event."
+ ),
+ )
+ horizon_days = serializers.IntegerField(help_text="Resolved prediction horizon in days.")
+ training_lookback_days = serializers.IntegerField(
+ help_text=(
+ "Training lookback in days, sized so the horizon leaves room for training examples. "
+ "Pass as 'training_lookback_days' to autoresearch-create."
+ ),
+ )
+ training_population = PopulationSpecField(
+ help_text=("Resolved training population filter. Pass as 'training_population' to autoresearch-create."),
+ )
+ inference_population = PopulationSpecField(
+ help_text=(
+ "Resolved inference (daily scoring) population filter. "
+ "Pass as 'inference_population' to autoresearch-create."
+ ),
+ )
+ output_person_property = serializers.CharField(
+ help_text="Suggested person property name for prediction scores. Pass as 'output_person_property' to autoresearch-create.",
+ )
+ notes = serializers.CharField(help_text="Usage notes and guidance for interpreting this resolved config.")
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 616a19eaec40..6b9fefd8d139 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -13,24 +13,38 @@ from dataclasses import fields
from typing import Any, cast
import structlog
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import viewsets
-from rest_framework.exceptions import NotFound
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.fields import empty
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
from posthog.api.documentation import PostHogAutoSchema
+from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.user import User
+from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from products.autoresearch.backend.facade import api
from products.autoresearch.backend.facade.access import has_autoresearch_access
-from products.autoresearch.backend.facade.contracts import PipelineNotFound
-
-from .serializers import AutoresearchPipelineCreateSerializer, AutoresearchPipelineSerializer
+from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFound
+
+from .serializers import (
+ AutoresearchPipelineCreateSerializer,
+ AutoresearchPipelineSerializer,
+ ResolvedTemplateSerializer,
+ ResolveTemplateRequestSerializer,
+ TemplateInfoSerializer,
+ ValidatePipelineRequestSerializer,
+ ValidatePipelineResponseSerializer,
+ resolve_target,
+ validate_event_target,
+)
logger = structlog.get_logger(__name__)
@@ -121,12 +135,19 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
schema = FacadePathParamSchema()
uuid_path_parameters = {"id": "A UUID string identifying this autoresearch pipeline."}
scope_object = "autoresearch"
- scope_object_read_actions = ["list", "retrieve"]
+ # Both HogQL actions also carry their own `required_scopes`, so a scoped token needs `query:read` too.
+ scope_object_read_actions = ["list", "retrieve", "validate_definition", "list_templates", "resolve_template"]
scope_object_write_actions = ["create", "update", "partial_update", "destroy"]
permission_classes = [AutoresearchAccessPermission]
serializer_class = AutoresearchPipelineSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ def get_throttles(self) -> list[BaseThrottle]:
+ # Several unsampled ClickHouse scans per call, so a personal API key gets the ClickHouse budget.
+ if self.action in ("resolve_template", "validate_definition"):
+ return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]
+ return super().get_throttles()
+
def get_serializer_class(self) -> type[AutoresearchPipelineSerializer | AutoresearchPipelineCreateSerializer]:
if self.action in ("create", "partial_update", "update"):
return AutoresearchPipelineCreateSerializer
@@ -192,3 +213,103 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
except PipelineNotFound:
raise NotFound("Pipeline not found.")
return Response(status=204)
+
+ @extend_schema(
+ responses={200: TemplateInfoSerializer(many=True)},
+ summary="List available templates",
+ description=(
+ "Return all built-in autoresearch prediction templates. "
+ "Each entry describes what the template predicts, its default horizon and prediction mode, "
+ "and whether it requires you to supply a target_event. "
+ "After choosing a template, call autoresearch-resolve-template-create to get a fully "
+ "resolved pipeline config ready to pass to autoresearch-create."
+ ),
+ )
+ @action(detail=False, methods=["get"], url_path="templates", pagination_class=None)
+ def list_templates(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return Response(TemplateInfoSerializer(instance=api.list_templates(), many=True).data)
+
+ @validated_request(
+ request_serializer=ResolveTemplateRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ResolvedTemplateSerializer,
+ description=(
+ "Resolved pipeline config. Pass target_event, horizon_days, training_lookback_days, "
+ "training_population, inference_population, and output_person_property directly "
+ "to autoresearch-create. Always run autoresearch-validate-create on the resolved "
+ "config before creating."
+ ),
+ ),
+ 400: OpenApiResponse(description="Unknown template key or missing required target_event override."),
+ },
+ summary="Resolve a template",
+ description=(
+ "Resolve a template key and optional overrides into a concrete pipeline config. "
+ "For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', "
+ "'return_after_first_use'), the target event is auto-resolved from your event schema — "
+ "check resolved_activity_event and activity_event_alternatives, then override if needed. "
+ "For 'feature_adoption' and 'repeat_key_behavior', supply target_event. "
+ "After resolving, call autoresearch-validate-create to check volume and warnings, "
+ "then autoresearch-create to create the pipeline."
+ ),
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="resolve-template",
+ required_scopes=["autoresearch:read", "query:read"],
+ )
+ def resolve_template(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ try:
+ resolved = api.resolve_template(
+ self.team_id,
+ template_key=data["template_key"],
+ target_event_override=data.get("target_event"),
+ horizon_days_override=data.get("horizon_days"),
+ user=cast(User, request.user),
+ )
+ except AutoresearchConflict as exc:
+ raise ValidationError(str(exc)) from exc
+ # The auto-resolved event is the team's own data, so it gets the same check as an override.
+ validate_event_target(resolved.target_event, error_key="target_event")
+ return Response(ResolvedTemplateSerializer(instance=resolved).data)
+
+ @validated_request(
+ request_serializer=ValidatePipelineRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ValidatePipelineResponseSerializer,
+ description="Validation result with volume estimates, base rate, and warnings.",
+ ),
+ },
+ summary="Validate a pipeline definition",
+ description=(
+ "Validate a proposed pipeline's target event and population before creating it. "
+ "Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: "
+ "'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other "
+ "'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create."
+ ),
+ )
+ @action(detail=False, methods=["post"], url_path="validate", required_scopes=["autoresearch:read", "query:read"])
+ def validate_definition(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ target_event, target_definition = resolve_target(
+ team=self.team,
+ target_event=data.get("target_event", ""),
+ target_definition=data.get("target_definition"),
+ request=request,
+ )
+ result = api.validate_definition(
+ self.team_id,
+ target_event=target_event,
+ target_definition=target_definition,
+ horizon_days=data.get("horizon_days", 7),
+ training_lookback_days=data.get("training_lookback_days", 180),
+ training_population=data["training_population"],
+ # Creation stores the training population when this is omitted or empty, so count the same one.
+ inference_population=data.get("inference_population") or data["training_population"],
+ user=cast(User, request.user),
+ )
+ return Response(ValidatePipelineResponseSerializer(instance=result).data)
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 19cbbe2cf977..c7fc5c1914ac 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -1,8 +1,9 @@
import uuid
from typing import Any
+import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -12,13 +13,42 @@ from rest_framework import status
from posthog.models import Organization, Team
from products.actions.backend.models.action import Action
+from products.autoresearch.backend.dataset.templates import TEMPLATES
+from products.autoresearch.backend.dataset.validation import ValidationResult, ValidationWarning
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
from products.autoresearch.backend.presentation.views.serializers import (
+ VALIDATION_WARNING_CODES,
AutoresearchPipelineCreateSerializer,
PopulationDefinitionField,
+ ValidationWarningSerializer,
)
from products.autoresearch.backend.testing import TeamScopedTestMixin
+MOCK_VALIDATION_OK = ValidationResult(
+ can_proceed=True,
+ requires_acknowledgement=False,
+ estimated_training_rows=500,
+ positive_count=100,
+ negative_count=400,
+ base_rate=0.2,
+ inference_population_size=500,
+ warnings=[],
+)
+
+MOCK_VALIDATION_ERROR = ValidationResult(
+ can_proceed=False,
+ requires_acknowledgement=False,
+ estimated_training_rows=5,
+ positive_count=5,
+ negative_count=0,
+ base_rate=1.0,
+ inference_population_size=5,
+ warnings=[
+ ValidationWarning(code="low_volume", message="Only 5 users found.", severity="error"),
+ ValidationWarning(code="low_positives", message="Only 5 positive examples.", severity="error"),
+ ],
+)
+
class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
def setUp(self):
@@ -148,6 +178,123 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
# ─────────────────────────────────────── validate action ──────────────────────────────────────
+ @patch(
+ "products.autoresearch.backend.facade.api._validate_pipeline_definition",
+ return_value=MOCK_VALIDATION_OK,
+ )
+ def test_validate_pipeline_success(self, _mock: MagicMock):
+ resp = self.client.post(
+ f"{self.base_url}/validate/",
+ {"target_event": "$signup", "horizon_days": 7},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["can_proceed"] is True
+ assert data["base_rate"] == pytest.approx(0.2)
+ assert data["warnings"] == []
+ assert _mock.call_args.kwargs["user"] == self.user
+
+ @patch(
+ "products.autoresearch.backend.facade.api._validate_pipeline_definition",
+ return_value=MOCK_VALIDATION_ERROR,
+ )
+ def test_validate_pipeline_with_errors(self, _mock: MagicMock):
+ resp = self.client.post(
+ f"{self.base_url}/validate/",
+ {"target_event": "$rare_event", "horizon_days": 7},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["can_proceed"] is False
+ assert len(data["warnings"]) == 2
+ assert data["warnings"][0]["severity"] == "error"
+
+ @parameterized.expand(
+ [
+ ("missing_target", {}),
+ ("list_shaped_target_definition", {"target_event": "$signup", "target_definition": [1]}),
+ ]
+ )
+ def test_validate_rejects(self, _name: str, body: dict):
+ resp = self.client.post(f"{self.base_url}/validate/", body, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand(
+ [
+ ("omitted", {}, {"kind": "ever_performed_target"}),
+ ("empty", {"inference_population": {}}, {"kind": "ever_performed_target"}),
+ ("given", {"inference_population": {"kind": "person_first_seen_within_days", "days": 14}}, None),
+ ]
+ )
+ @patch(
+ "products.autoresearch.backend.facade.api._validate_pipeline_definition",
+ return_value=MOCK_VALIDATION_OK,
+ )
+ def test_validate_previews_the_population_creation_would_store(
+ self, _name: str, extra: dict, expected: dict | None, _mock: MagicMock
+ ):
+ body = {"target_event": "$signup", "training_population": {"kind": "ever_performed_target"}, **extra}
+ resp = self.client.post(f"{self.base_url}/validate/", body, format="json")
+ assert resp.status_code == status.HTTP_200_OK
+ expected = expected if expected is not None else extra["inference_population"]
+ assert _mock.call_args.kwargs["inference_population"] == expected
+
+ @parameterized.expand(
+ [
+ ("validate", "validate", {"target_event": "$signup"}),
+ ("resolve_template", "resolve-template", {"template_key": "likely_active_soon"}),
+ ]
+ )
+ @patch(
+ "products.autoresearch.backend.dataset.templates.resolve_activity_event",
+ return_value=("$pageview", []),
+ )
+ @patch(
+ "products.autoresearch.backend.facade.api._validate_pipeline_definition",
+ return_value=MOCK_VALIDATION_OK,
+ )
+ def test_query_backed_helpers_need_the_query_scope(
+ self, _name: str, path: str, body: dict, _validate: MagicMock, _resolve: MagicMock
+ ):
+ self.client.logout()
+ read_only = self.create_personal_api_key_with_scopes(["autoresearch:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {read_only}")
+ assert (
+ self.client.post(f"{self.base_url}/{path}/", body, format="json").status_code == status.HTTP_403_FORBIDDEN
+ )
+ with_query = self.create_personal_api_key_with_scopes(["autoresearch:read", "query:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_query}")
+ assert self.client.post(f"{self.base_url}/{path}/", body, format="json").status_code == status.HTTP_200_OK
+
+ @parameterized.expand(
+ [
+ ("validate", "validate/", ["autoresearch:read", "query:read"], status.HTTP_200_OK),
+ ("create", "", ["autoresearch:write"], status.HTTP_201_CREATED),
+ ]
+ )
+ @patch(
+ "products.autoresearch.backend.facade.api._validate_pipeline_definition",
+ return_value=MOCK_VALIDATION_OK,
+ )
+ def test_action_targets_need_the_action_scope(
+ self, _name: str, path: str, scopes: list[str], ok_status: int, _mock: MagicMock
+ ):
+ action = Action.objects.create(
+ team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]
+ )
+ body = {"name": "Action Pipeline", "target_definition": {"type": "action", "action_id": action.id}}
+ self.client.logout()
+ without = self.create_personal_api_key_with_scopes(scopes)
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {without}")
+ resp = self.client.post(f"{self.base_url}/{path}", body, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert resp.json()["attr"] == "target_definition"
+ with_action = self.create_personal_api_key_with_scopes([*scopes, "action:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_action}")
+ assert self.client.post(f"{self.base_url}/{path}", body, format="json").status_code == ok_status
+
# ──────────────────────────────────────── train action ────────────────────────────────────────
# ──────────────────────────────────── update restrictions ─────────────────────────────────────
@@ -244,6 +391,84 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
# ─────────────────────────────────── nested resources ─────────────────────────────────────────
+ # ──────────────────────────────────────────── templates ────────────────────────────────────────────
+
+ def test_list_templates_returns_every_template(self):
+ resp = self.client.get(f"{self.base_url}/templates/")
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert {t["key"] for t in data} == set(TEMPLATES)
+ for field in (
+ "key",
+ "display_name",
+ "description",
+ "default_horizon_days",
+ "requires_user_event",
+ "requires_activity_resolution",
+ "notes",
+ ):
+ assert field in data[0]
+
+ @patch(
+ "products.autoresearch.backend.dataset.templates.resolve_activity_event",
+ return_value=("$pageview", ["$screen"]),
+ )
+ def test_resolve_template_runs_as_the_request_user(self, resolve_activity: MagicMock):
+ resp = self.client.post(
+ f"{self.base_url}/resolve-template/",
+ {"template_key": "likely_active_soon"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["target_event"] == "$pageview"
+ assert data["horizon_days"] == 7
+ assert data["activity_event_alternatives"] == ["$screen"]
+ assert data["training_lookback_days"] == 180
+ for field in ("training_population", "inference_population", "output_person_property", "suggested_name"):
+ assert field in data
+ assert resolve_activity.call_args.kwargs["user"] == self.user
+
+ @patch(
+ "products.autoresearch.backend.dataset.templates.resolve_activity_event",
+ return_value=("$pageview", []),
+ )
+ def test_resolve_template_horizon_override(self, _mock: MagicMock):
+ resp = self.client.post(
+ f"{self.base_url}/resolve-template/",
+ {"template_key": "likely_active_soon", "horizon_days": 30},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["horizon_days"] == 30
+
+ def test_resolve_template_feature_adoption_uses_the_supplied_event(self):
+ resp = self.client.post(
+ f"{self.base_url}/resolve-template/",
+ {"template_key": "feature_adoption", "target_event": "feature_clicked"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["target_event"] == "feature_clicked"
+
+ @parameterized.expand(
+ [
+ ("missing_required_target_event", {"template_key": "feature_adoption"}),
+ ("unknown_template_key", {"template_key": "not_a_real_template"}),
+ ("own_prediction_event", {"template_key": "feature_adoption", "target_event": "autoresearch_prediction"}),
+ ("unsafe_target_event", {"template_key": "repeat_key_behavior", "target_event": "signup`whoami`"}),
+ ]
+ )
+ def test_resolve_template_rejects(self, _name: str, body: dict):
+ resp = self.client.post(f"{self.base_url}/resolve-template/", body, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestValidationWarningSerializer(SimpleTestCase):
+ def test_help_text_names_every_code_the_validator_emits(self) -> None:
+ help_text = str(ValidationWarningSerializer().fields["code"].help_text)
+ assert all(f"'{code}'" in help_text for code in VALIDATION_WARNING_CODES)
+
class TestPipelineCreateSerializerValidation(SimpleTestCase):
# Field- and target-shape validation runs in memory, so these cases never need a DB.
@@ -282,6 +507,11 @@ class TestPipelineCreateSerializerValidation(SimpleTestCase):
("days_not_int", {"kind": "person_first_seen_within_days", "days": "14"}),
("days_out_of_range", {"kind": "performed_event_within_days", "days": 100000}),
("missing_event_for_repeat", {"kind": "ever_performed_event"}),
+ ("too_many_filters", {"properties": [{"key": "k", "type": "person", "operator": "is_set"}] * 21}),
+ (
+ "too_many_filter_values",
+ {"properties": [{"key": "k", "type": "person", "operator": "exact", "value": list(range(201))}]},
+ ),
]
)
def test_uncompilable_population_rejected(self, _name: str, population: Any) -> None:
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 105683b628c4..bce68997e31e 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -389,6 +389,228 @@ export interface PatchedAutoresearchPipelineCreateApi {
output_person_property?: string
}
+/**
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior
+ */
+export type TemplateKeyEnumApi = (typeof TemplateKeyEnumApi)[keyof typeof TemplateKeyEnumApi]
+
+export const TemplateKeyEnumApi = {
+ LikelyActiveSoon: 'likely_active_soon',
+ AtRiskOfInactivity: 'at_risk_of_inactivity',
+ ReturnAfterFirstUse: 'return_after_first_use',
+ FeatureAdoption: 'feature_adoption',
+ RepeatKeyBehavior: 'repeat_key_behavior',
+} as const
+
+export interface ResolveTemplateRequestApi {
+ /** Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ template_key: TemplateKeyEnumApi
+ /** Event name to use as the prediction target. Required for 'feature_adoption' and 'repeat_key_behavior'. Optional override for activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'); omit to use the auto-resolved event. To predict an action, create the pipeline with target_definition after resolving. */
+ target_event?: string
+ /**
+ * Override the template's default prediction horizon in days.
+ * @minimum 1
+ * @maximum 365
+ */
+ horizon_days?: number
+}
+
+/**
+ * Resolved training population filter. Pass as 'training_population' to autoresearch-create.
+ */
+export type ResolvedTemplateApiTrainingPopulation = { [key: string]: unknown }
+
+/**
+ * Resolved inference (daily scoring) population filter. Pass as 'inference_population' to autoresearch-create.
+ */
+export type ResolvedTemplateApiInferencePopulation = { [key: string]: unknown }
+
+export interface ResolvedTemplateApi {
+ /** The template key that was resolved. Pass it back to re-resolve with a different target_event.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ template_key: TemplateKeyEnumApi
+ /** Human-readable template name. */
+ display_name: string
+ /** What this template predicts. */
+ description: string
+ /** Suggested pipeline name. Pass as 'name' to autoresearch-create. */
+ suggested_name: string
+ /** Resolved target event. Pass as 'target_event' to autoresearch-create. For activity-based templates this is the auto-resolved activity event (or your override). */
+ target_event: string
+ /**
+ * Activity event found in your event schema, populated only for templates that auto-resolve the target ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'). Null for templates where you supply target_event directly.
+ * @nullable
+ */
+ resolved_activity_event: string | null
+ /** Other viable activity events found in your schema. If the resolved event is not the right signal, re-resolve with one of these as target_event. */
+ activity_event_alternatives: string[]
+ /** Resolved prediction horizon in days. */
+ horizon_days: number
+ /** Training lookback in days, sized so the horizon leaves room for training examples. Pass as 'training_lookback_days' to autoresearch-create. */
+ training_lookback_days: number
+ /** Resolved training population filter. Pass as 'training_population' to autoresearch-create. */
+ training_population: ResolvedTemplateApiTrainingPopulation
+ /** Resolved inference (daily scoring) population filter. Pass as 'inference_population' to autoresearch-create. */
+ inference_population: ResolvedTemplateApiInferencePopulation
+ /** Suggested person property name for prediction scores. Pass as 'output_person_property' to autoresearch-create. */
+ output_person_property: string
+ /** Usage notes and guidance for interpreting this resolved config. */
+ notes: string
+}
+
+export interface TemplateInfoApi {
+ /** Template identifier, e.g. 'likely_active_soon'. Pass to autoresearch-resolve-template-create.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ key: TemplateKeyEnumApi
+ /** Human-readable template name. */
+ display_name: string
+ /** What this template predicts and who it is for. */
+ description: string
+ /** Default prediction horizon in days. Can be overridden when resolving. */
+ default_horizon_days: number
+ /** If true, you must supply a target_event when resolving — the template does not auto-select one. Required for 'feature_adoption' and 'repeat_key_behavior'. */
+ requires_user_event: boolean
+ /** If true, the target event is automatically resolved from your event schema ($pageview, $screen, or the highest-volume non-noisy event). You can override the resolved event when resolving the template. */
+ requires_activity_resolution: boolean
+ /** Usage guidance and implementation notes. */
+ notes: string
+}
+
+/**
+ * Optional target definition. Pass {"type": "action", "action_id": N} to predict a PostHog action (multi-step / property / autocapture matcher) instead of a single event.
+ */
+export type ValidatePipelineRequestApiTargetDefinition =
+ | {
+ type: 'event'
+ }
+ | {
+ type: 'action'
+ /**
+ * ID of the action to predict.
+ * @minimum 1
+ */
+ action_id: number
+ }
+
+/**
+ * Population filter for training examples. Use {} for all identified users.
+ */
+export type ValidatePipelineRequestApiTrainingPopulation = { [key: string]: unknown }
+
+/**
+ * Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it.
+ */
+export type ValidatePipelineRequestApiInferencePopulation = { [key: string]: unknown }
+
+export interface ValidatePipelineRequestApi {
+ /** Event name to predict, e.g. '$pageview'. Must exist in the team's event schema. Omit when predicting an action target (pass target_definition instead). */
+ target_event?: string
+ /** Optional target definition. Pass {"type": "action", "action_id": N} to predict a PostHog action (multi-step / property / autocapture matcher) instead of a single event. */
+ target_definition?: ValidatePipelineRequestApiTargetDefinition
+ /**
+ * Predict whether the target event occurs within this many days.
+ * @minimum 1
+ * @maximum 365
+ */
+ horizon_days?: number
+ /**
+ * How far back to look for training examples. Default: 180.
+ * @minimum 7
+ * @maximum 730
+ */
+ training_lookback_days?: number
+ /** Population filter for training examples. Use {} for all identified users. */
+ training_population?: ValidatePipelineRequestApiTrainingPopulation
+ /** Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it. */
+ inference_population?: ValidatePipelineRequestApiInferencePopulation
+}
+
+/**
+ * * `info` - info
+ * * `warning` - warning
+ * * `error` - error
+ */
+export type ValidationWarningSeverityEnumApi =
+ (typeof ValidationWarningSeverityEnumApi)[keyof typeof ValidationWarningSeverityEnumApi]
+
+export const ValidationWarningSeverityEnumApi = {
+ Info: 'info',
+ Warning: 'warning',
+ Error: 'error',
+} as const
+
+export interface ValidationWarningApi {
+ /** Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail: fix the definition before creating. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
+ code: string
+ /** Human-readable warning description. */
+ message: string
+ /** Severity level. 'error' means training would fail or the data is too thin for a reliable model; see 'code' for which. 'warning' is worth acknowledging. Creation enforces none of them.
+ *
+ * * `info` - info
+ * * `warning` - warning
+ * * `error` - error */
+ severity: ValidationWarningSeverityEnumApi
+}
+
+export interface ValidatePipelineResponseApi {
+ /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
+ can_proceed: boolean
+ /** True if there are non-blocking warnings the user should acknowledge before proceeding. */
+ requires_acknowledgement: boolean
+ /**
+ * Estimated number of user-level training rows based on the population and lookback window.
+ * @nullable
+ */
+ estimated_training_rows: number | null
+ /**
+ * Estimated number of positive examples (users who performed the target event).
+ * @nullable
+ */
+ positive_count: number | null
+ /**
+ * Estimated number of negative examples.
+ * @nullable
+ */
+ negative_count: number | null
+ /**
+ * Fraction of the training population that performed the target event.
+ * @nullable
+ */
+ base_rate: number | null
+ /**
+ * Estimated number of users in the inference (daily scoring) population.
+ * @nullable
+ */
+ inference_population_size: number | null
+ /** List of validation warnings. Check 'severity' and 'code'. */
+ warnings: ValidationWarningApi[]
+ /**
+ * Why validation did not run, or null when it did. A query error in the definition itself is passed through; any other failure is a generic message and the detail is logged.
+ * @nullable
+ */
+ error: string | null
+}
+
export type AutoresearchListParams = {
/**
* Number of results to return per page.
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index 159524857b38..f32493cf9092 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -14,6 +14,11 @@ import type {
AutoresearchPipelineCreateApi,
PaginatedAutoresearchPipelineListApi,
PatchedAutoresearchPipelineCreateApi,
+ ResolveTemplateRequestApi,
+ ResolvedTemplateApi,
+ TemplateInfoApi,
+ ValidatePipelineRequestApi,
+ ValidatePipelineResponseApi,
} from './api.schemas'
export const getAutoresearchListUrl = (projectId: string, params?: AutoresearchListParams) => {
@@ -163,3 +168,63 @@ export const autoresearchDestroy = async (projectId: string, id: string, options
method: 'DELETE',
})
}
+
+export const getAutoresearchResolveTemplateCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/autoresearch/resolve-template/`
+}
+
+/**
+ * Resolve a template key and optional overrides into a concrete pipeline config. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target event is auto-resolved from your event schema — check resolved_activity_event and activity_event_alternatives, then override if needed. For 'feature_adoption' and 'repeat_key_behavior', supply target_event. After resolving, call autoresearch-validate-create to check volume and warnings, then autoresearch-create to create the pipeline.
+ * @summary Resolve a template
+ */
+export const autoresearchResolveTemplateCreate = async (
+ projectId: string,
+ resolveTemplateRequestApi: ResolveTemplateRequestApi,
+ options?: RequestInit
+): Promise<ResolvedTemplateApi> => {
+ return apiMutator<ResolvedTemplateApi>(getAutoresearchResolveTemplateCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(resolveTemplateRequestApi),
+ })
+}
+
+export const getAutoresearchTemplatesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/autoresearch/templates/`
+}
+
+/**
+ * Return all built-in autoresearch prediction templates. Each entry describes what the template predicts, its default horizon and prediction mode, and whether it requires you to supply a target_event. After choosing a template, call autoresearch-resolve-template-create to get a fully resolved pipeline config ready to pass to autoresearch-create.
+ * @summary List available templates
+ */
+export const autoresearchTemplatesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<TemplateInfoApi[]> => {
+ return apiMutator<TemplateInfoApi[]>(getAutoresearchTemplatesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchValidateCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/autoresearch/validate/`
+}
+
+/**
+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
+ * @summary Validate a pipeline definition
+ */
+export const autoresearchValidateCreate = async (
+ projectId: string,
+ validatePipelineRequestApi?: ValidatePipelineRequestApi,
+ options?: RequestInit
+): Promise<ValidatePipelineResponseApi> => {
+ return apiMutator<ValidatePipelineResponseApi>(getAutoresearchValidateCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(validatePipelineRequestApi),
+ })
+}
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index 374da72802dd..e74410ed3d80 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -344,3 +344,99 @@ export const AutoresearchPartialUpdateBody = /* @__PURE__ */ zod.object({
"Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines."
),
})
+
+/**
+ * Resolve a template key and optional overrides into a concrete pipeline config. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target event is auto-resolved from your event schema — check resolved_activity_event and activity_event_alternatives, then override if needed. For 'feature_adoption' and 'repeat_key_behavior', supply target_event. After resolving, call autoresearch-validate-create to check volume and warnings, then autoresearch-create to create the pipeline.
+ * @summary Resolve a template
+ */
+export const autoresearchResolveTemplateCreateBodyHorizonDaysMax = 365
+
+export const AutoresearchResolveTemplateCreateBody = /* @__PURE__ */ zod.object({
+ template_key: zod
+ .enum([
+ 'likely_active_soon',
+ 'at_risk_of_inactivity',
+ 'return_after_first_use',
+ 'feature_adoption',
+ 'repeat_key_behavior',
+ ])
+ .describe(
+ '\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'
+ )
+ .describe(
+ 'Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.\n\n\* `likely_active_soon` - Likely Active Soon\n\* `at_risk_of_inactivity` - At Risk Of Inactivity\n\* `return_after_first_use` - Return After First Use\n\* `feature_adoption` - Feature Adoption\n\* `repeat_key_behavior` - Repeat Key Behavior'
+ ),
+ target_event: zod
+ .string()
+ .optional()
+ .describe(
+ "Event name to use as the prediction target. Required for 'feature_adoption' and 'repeat_key_behavior'. Optional override for activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'); omit to use the auto-resolved event. To predict an action, create the pipeline with target_definition after resolving."
+ ),
+ horizon_days: zod
+ .number()
+ .min(1)
+ .max(autoresearchResolveTemplateCreateBodyHorizonDaysMax)
+ .optional()
+ .describe("Override the template's default prediction horizon in days."),
+})
+
+/**
+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
+ * @summary Validate a pipeline definition
+ */
+export const autoresearchValidateCreateBodyTargetEventDefault = ``
+export const autoresearchValidateCreateBodyHorizonDaysDefault = 7
+export const autoresearchValidateCreateBodyHorizonDaysMax = 365
+
+export const autoresearchValidateCreateBodyTrainingLookbackDaysDefault = 180
+export const autoresearchValidateCreateBodyTrainingLookbackDaysMin = 7
+export const autoresearchValidateCreateBodyTrainingLookbackDaysMax = 730
+
+export const AutoresearchValidateCreateBody = /* @__PURE__ */ zod.object({
+ target_event: zod
+ .string()
+ .default(autoresearchValidateCreateBodyTargetEventDefault)
+ .describe(
+ "Event name to predict, e.g. '$pageview'. Must exist in the team's event schema. Omit when predicting an action target (pass target_definition instead)."
+ ),
+ target_definition: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['event']),
+ })
+ .describe('Predict target_event. The default when target_definition is omitted.'),
+ zod
+ .object({
+ type: zod.enum(['action']),
+ action_id: zod.number().min(1).describe('ID of the action to predict.'),
+ })
+ .describe('Predict a PostHog action in this project.'),
+ ])
+ .optional()
+ .describe(
+ 'Optional target definition. Pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action (multi-step \/ property \/ autocapture matcher) instead of a single event.'
+ ),
+ horizon_days: zod
+ .number()
+ .min(1)
+ .max(autoresearchValidateCreateBodyHorizonDaysMax)
+ .default(autoresearchValidateCreateBodyHorizonDaysDefault)
+ .describe('Predict whether the target event occurs within this many days.'),
+ training_lookback_days: zod
+ .number()
+ .min(autoresearchValidateCreateBodyTrainingLookbackDaysMin)
+ .max(autoresearchValidateCreateBodyTrainingLookbackDaysMax)
+ .default(autoresearchValidateCreateBodyTrainingLookbackDaysDefault)
+ .describe('How far back to look for training examples. Default: 180.'),
+ training_population: zod
+ .looseObject({})
+ .optional()
+ .describe('Population filter for training examples. Use {} for all identified users.'),
+ inference_population: zod
+ .looseObject({})
+ .optional()
+ .describe(
+ 'Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it.'
+ ),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c8940914bd9a..8e40086cfe04 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79710,6 +79710,91 @@ export namespace Schemas {
Stopped: 'stopped',
} as const;
+ /**
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior
+ */
+ export type TemplateKeyEnum = typeof TemplateKeyEnum[keyof typeof TemplateKeyEnum];
+
+
+ export const TemplateKeyEnum = {
+ LikelyActiveSoon: 'likely_active_soon',
+ AtRiskOfInactivity: 'at_risk_of_inactivity',
+ ReturnAfterFirstUse: 'return_after_first_use',
+ FeatureAdoption: 'feature_adoption',
+ RepeatKeyBehavior: 'repeat_key_behavior',
+ } as const;
+
+ export interface ResolveTemplateRequest {
+ /** Template to resolve. Use autoresearch-templates-list to see all available templates with descriptions. Required.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ template_key: TemplateKeyEnum;
+ /** Event name to use as the prediction target. Required for 'feature_adoption' and 'repeat_key_behavior'. Optional override for activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'); omit to use the auto-resolved event. To predict an action, create the pipeline with target_definition after resolving. */
+ target_event?: string;
+ /**
+ * Override the template's default prediction horizon in days.
+ * @minimum 1
+ * @maximum 365
+ */
+ horizon_days?: number;
+ }
+
+ /**
+ * Resolved training population filter. Pass as 'training_population' to autoresearch-create.
+ */
+ export type ResolvedTemplateTrainingPopulation = { [key: string]: unknown };
+
+ /**
+ * Resolved inference (daily scoring) population filter. Pass as 'inference_population' to autoresearch-create.
+ */
+ export type ResolvedTemplateInferencePopulation = { [key: string]: unknown };
+
+ export interface ResolvedTemplate {
+ /** The template key that was resolved. Pass it back to re-resolve with a different target_event.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ template_key: TemplateKeyEnum;
+ /** Human-readable template name. */
+ display_name: string;
+ /** What this template predicts. */
+ description: string;
+ /** Suggested pipeline name. Pass as 'name' to autoresearch-create. */
+ suggested_name: string;
+ /** Resolved target event. Pass as 'target_event' to autoresearch-create. For activity-based templates this is the auto-resolved activity event (or your override). */
+ target_event: string;
+ /**
+ * Activity event found in your event schema, populated only for templates that auto-resolve the target ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'). Null for templates where you supply target_event directly.
+ * @nullable
+ */
+ resolved_activity_event: string | null;
+ /** Other viable activity events found in your schema. If the resolved event is not the right signal, re-resolve with one of these as target_event. */
+ activity_event_alternatives: string[];
+ /** Resolved prediction horizon in days. */
+ horizon_days: number;
+ /** Training lookback in days, sized so the horizon leaves room for training examples. Pass as 'training_lookback_days' to autoresearch-create. */
+ training_lookback_days: number;
+ /** Resolved training population filter. Pass as 'training_population' to autoresearch-create. */
+ training_population: ResolvedTemplateTrainingPopulation;
+ /** Resolved inference (daily scoring) population filter. Pass as 'inference_population' to autoresearch-create. */
+ inference_population: ResolvedTemplateInferencePopulation;
+ /** Suggested person property name for prediction scores. Pass as 'output_person_property' to autoresearch-create. */
+ output_person_property: string;
+ /** Usage notes and guidance for interpreting this resolved config. */
+ notes: string;
+ }
+
/**
* * `accepted` - accepted
* * `target_finished` - target_finished
@@ -91610,6 +91695,29 @@ export namespace Schemas {
tracing_session_id_attribute_keys: string[];
}
+ export interface TemplateInfo {
+ /** Template identifier, e.g. 'likely_active_soon'. Pass to autoresearch-resolve-template-create.
+ *
+ * * `likely_active_soon` - Likely Active Soon
+ * * `at_risk_of_inactivity` - At Risk Of Inactivity
+ * * `return_after_first_use` - Return After First Use
+ * * `feature_adoption` - Feature Adoption
+ * * `repeat_key_behavior` - Repeat Key Behavior */
+ key: TemplateKeyEnum;
+ /** Human-readable template name. */
+ display_name: string;
+ /** What this template predicts and who it is for. */
+ description: string;
+ /** Default prediction horizon in days. Can be overridden when resolving. */
+ default_horizon_days: number;
+ /** If true, you must supply a target_event when resolving — the template does not auto-select one. Required for 'feature_adoption' and 'repeat_key_behavior'. */
+ requires_user_event: boolean;
+ /** If true, the target event is automatically resolved from your event schema ($pageview, $screen, or the highest-volume non-noisy event). You can override the resolved event when resolving the template. */
+ requires_activity_resolution: boolean;
+ /** Usage guidance and implementation notes. */
+ notes: string;
+ }
+
/**
* * `none` - none
* * `last` - last
@@ -92485,6 +92593,119 @@ export namespace Schemas {
notes: string[];
}
+ /**
+ * Optional target definition. Pass {"type": "action", "action_id": N} to predict a PostHog action (multi-step / property / autocapture matcher) instead of a single event.
+ */
+ export type ValidatePipelineRequestTargetDefinition = {
+ type: 'event';
+ } | {
+ type: 'action';
+ /**
+ * ID of the action to predict.
+ * @minimum 1
+ */
+ action_id: number;
+ };
+
+ /**
+ * Population filter for training examples. Use {} for all identified users.
+ */
+ export type ValidatePipelineRequestTrainingPopulation = { [key: string]: unknown };
+
+ /**
+ * Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it.
+ */
+ export type ValidatePipelineRequestInferencePopulation = { [key: string]: unknown };
+
+ export interface ValidatePipelineRequest {
+ /** Event name to predict, e.g. '$pageview'. Must exist in the team's event schema. Omit when predicting an action target (pass target_definition instead). */
+ target_event?: string;
+ /** Optional target definition. Pass {"type": "action", "action_id": N} to predict a PostHog action (multi-step / property / autocapture matcher) instead of a single event. */
+ target_definition?: ValidatePipelineRequestTargetDefinition;
+ /**
+ * Predict whether the target event occurs within this many days.
+ * @minimum 1
+ * @maximum 365
+ */
+ horizon_days?: number;
+ /**
+ * How far back to look for training examples. Default: 180.
+ * @minimum 7
+ * @maximum 730
+ */
+ training_lookback_days?: number;
+ /** Population filter for training examples. Use {} for all identified users. */
+ training_population?: ValidatePipelineRequestTrainingPopulation;
+ /** Population filter for daily scoring. When omitted or empty, the training population is counted, as creation stores it. */
+ inference_population?: ValidatePipelineRequestInferencePopulation;
+ }
+
+ /**
+ * * `info` - info
+ * * `warning` - warning
+ * * `error` - error
+ */
+ export type ValidationWarningSeverityEnum = typeof ValidationWarningSeverityEnum[keyof typeof ValidationWarningSeverityEnum];
+
+
+ export const ValidationWarningSeverityEnum = {
+ Info: 'info',
+ Warning: 'warning',
+ Error: 'error',
+ } as const;
+
+ export interface ValidationWarning {
+ /** Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail: fix the definition before creating. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
+ code: string;
+ /** Human-readable warning description. */
+ message: string;
+ /** Severity level. 'error' means training would fail or the data is too thin for a reliable model; see 'code' for which. 'warning' is worth acknowledging. Creation enforces none of them.
+ *
+ * * `info` - info
+ * * `warning` - warning
+ * * `error` - error */
+ severity: ValidationWarningSeverityEnum;
+ }
+
+ export interface ValidatePipelineResponse {
+ /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
+ can_proceed: boolean;
+ /** True if there are non-blocking warnings the user should acknowledge before proceeding. */
+ requires_acknowledgement: boolean;
+ /**
+ * Estimated number of user-level training rows based on the population and lookback window.
+ * @nullable
+ */
+ estimated_training_rows: number | null;
+ /**
+ * Estimated number of positive examples (users who performed the target event).
+ * @nullable
+ */
+ positive_count: number | null;
+ /**
+ * Estimated number of negative examples.
+ * @nullable
+ */
+ negative_count: number | null;
+ /**
+ * Fraction of the training population that performed the target event.
+ * @nullable
+ */
+ base_rate: number | null;
+ /**
+ * Estimated number of users in the inference (daily scoring) population.
+ * @nullable
+ */
+ inference_population_size: number | null;
+ /** List of validation warnings. Check 'severity' and 'code'. */
+ warnings: ValidationWarning[];
+ /**
+ * Why validation did not run, or null when it did. A query error in the definition itself is passed through; any other failure is a generic message and the detail is logged.
+ * @nullable
+ */
+ error: string | null;
+ }
+
/**
* Request body for POST /api/users/verify_email/.
*/