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 dataset validation and the validate command (6/22) (#88794)

Andrew Maguiredcd1bff9c128
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
index 43633fad3de1..a9bdf03689fa 100644
--- a/products/autoresearch/backend/dataset/AGENTS.md
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -20,7 +20,7 @@ Nothing here trains or scores anything. It is the shared vocabulary that `../tra
Also here: `_compile_population_filters()` (property filters → HogQL; a cohort filter, an unknown operator, or a filter without a `type` raises rather than being skipped), `_build_population_kind_conditions()` (semantic population kinds → HogQL, see below), `build_target_condition()` (event or action target → predicate), `NUM_FOLDS = 5` with fold 0 as holdout, and `IDENTIFIED_USERS_ONLY`.
- `validation.py`
- Pre-flight viability. `validate_pipeline_definition()` answers "is there enough here to learn anything?" before a run is launched — `MIN_TRAINING_ROWS` (100), `MIN_POSITIVE_EXAMPLES` (20), `MIN_IDENTIFIED_FRACTION` (0.5).
+ Pre-flight viability. `validate_pipeline_definition()` answers "is there enough here to learn anything?" before a run is launched — `MIN_TRAINING_ROWS` (100), `MIN_POSITIVE_EXAMPLES` and `MIN_NEGATIVE_EXAMPLES` (20 each, because holdout AUC is undefined with one class), `MIN_IDENTIFIED_FRACTION` (0.5). The window validated is the configured `training_lookback_days`, unclamped, so the estimate describes the data training will see.
Returns a `ValidationResult` carrying `ValidationWarning`s rather than raising, because the API surfaces them as advice.
- `templates.py`
Built-in starting points. A template resolves to the same pipeline config shape as a fully custom pipeline, so creation and validation behave identically either way — there is no separate template code path downstream.
diff --git a/products/autoresearch/backend/dataset/test_validation.py b/products/autoresearch/backend/dataset/test_validation.py
new file mode 100644
index 000000000000..dc1d730c8b67
--- /dev/null
+++ b/products/autoresearch/backend/dataset/test_validation.py
@@ -0,0 +1,158 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.dataset.validation import (
+ ValidationResult,
+ _run_validation,
+ validate_pipeline_definition,
+)
+
+
+def _mock_rows(positives: int, total: int, identified: int | None = None) -> list[list[list[int]]]:
+ # Query order: eligible count, sampled labeler, inference count. Sample size
+ # equals total so the extrapolated positives line up with the input.
+ eligible_identified = total if identified is None else identified
+ return [
+ [[eligible_identified, total]],
+ [[eligible_identified, positives]],
+ [[eligible_identified]],
+ ]
+
+
+class TestValidationWarnings(BaseTest):
+ def _run(
+ self,
+ positives: int,
+ total: int,
+ horizon_days: int = 7,
+ training_lookback_days: int = 180,
+ identified: int | None = None,
+ ) -> ValidationResult:
+ with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
+ mock_run.side_effect = _mock_rows(positives, total, identified=identified)
+ return _run_validation(
+ team=self.team,
+ target_event="$pageview",
+ horizon_days=horizon_days,
+ training_lookback_days=training_lookback_days,
+ training_population={},
+ inference_population={},
+ )
+
+ def test_ok_result_has_no_warnings(self) -> None:
+ result = self._run(positives=100, total=1000)
+ assert result.can_proceed is True
+ assert result.requires_acknowledgement is False
+ assert result.warnings == []
+ assert result.base_rate == 0.1
+
+ @parameterized.expand(
+ [
+ ("low_volume", 10, 50, "low_volume"),
+ ("zero_users", 0, 0, "low_volume"),
+ ("low_positives", 5, 1000, "low_positives"),
+ ("low_negatives", 995, 1000, "low_negatives"),
+ ]
+ )
+ def test_hard_errors_block_proceeding(self, _name: str, positives: int, total: int, code: str) -> None:
+ result = self._run(positives=positives, total=total)
+ codes = [w.code for w in result.warnings]
+ assert code in codes
+ assert result.can_proceed is False
+
+ def test_moderate_volume_is_warning(self) -> None:
+ result = self._run(positives=30, total=200)
+ codes = [w.code for w in result.warnings]
+ assert "moderate_volume" in codes
+ assert result.can_proceed is True
+ assert result.requires_acknowledgement is True
+
+ def test_extreme_imbalance_is_warning(self) -> None:
+ result = self._run(positives=1, total=10000)
+ codes = [w.code for w in result.warnings]
+ assert "extreme_imbalance" in codes
+
+ def test_near_universal_is_warning(self) -> None:
+ result = self._run(positives=970, total=1000)
+ codes = [w.code for w in result.warnings]
+ assert "near_universal" in codes
+ assert result.can_proceed is True
+
+ def test_mostly_anonymous_population_is_warning(self) -> None:
+ result = self._run(positives=40, total=1000, identified=200)
+ codes = [w.code for w in result.warnings]
+ assert "mostly_anonymous_population" in codes
+ assert result.can_proceed is True
+ assert result.estimated_training_rows == 200
+
+ def test_majority_identified_population_has_no_anonymous_warning(self) -> None:
+ result = self._run(positives=100, total=1000, identified=900)
+ 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:
+ with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
+ mock_run.side_effect = RuntimeError("CH is down")
+ result = validate_pipeline_definition(
+ team=self.team,
+ target_event="$pageview",
+ horizon_days=7,
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ )
+ assert result.can_proceed is False
+ assert result.error is not None
+ assert "CH is down" in result.error
+
+ @parameterized.expand([("short_horizon_floors_at_30", 7, 30), ("long_horizon_is_4x", 14, 56)])
+ def test_inference_preview_uses_scoring_lookback(
+ 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.
+ 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=horizon_days,
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ )
+ inference_query = mock_run.call_args_list[2].kwargs["query"]
+ assert inference_query.values["lookback"] == expected_lookback
+
+ def test_training_window_is_the_configured_lookback(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=1,
+ training_lookback_days=2,
+ training_population={},
+ inference_population={},
+ )
+ eligible_query = mock_run.call_args_list[0].kwargs["query"]
+ labeler_query = mock_run.call_args_list[1].kwargs["query"]
+ assert eligible_query.values["lookback"] == 2
+ assert labeler_query.values["lookback"] == 2
+
+ def test_every_count_runs_as_the_given_user(self) -> None:
+ with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
+ mock_run.side_effect = _mock_rows(100, 1000)
+ validate_pipeline_definition(
+ team=self.team,
+ target_event="$pageview",
+ horizon_days=7,
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ user=self.user,
+ )
+ assert len(mock_run.call_args_list) == 3
+ assert all(call.kwargs["user"] is self.user for call in mock_run.call_args_list)
diff --git a/products/autoresearch/backend/dataset/validation.py b/products/autoresearch/backend/dataset/validation.py
new file mode 100644
index 000000000000..0f448a8a207c
--- /dev/null
+++ b/products/autoresearch/backend/dataset/validation.py
@@ -0,0 +1,310 @@
+from dataclasses import field
+from typing import Any, Optional
+
+import structlog
+
+from posthog.schema import HogQLQuery
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.autoresearch.backend.dataset.labeling import (
+ IDENTIFIED_USERS_ONLY,
+ _build_population_conditions,
+ _build_population_kind_conditions,
+ _identified_users_and_clause,
+ _target_condition_for,
+ build_eligible_count_sql,
+ build_random_t0_labeler_sql,
+)
+from products.autoresearch.backend.query import run_hogql_rows
+
+logger = structlog.get_logger(__name__)
+
+# Minimum number of labeled examples needed to train a meaningful model. Both classes
+# need examples: holdout AUC is undefined when every label is the same.
+MIN_TRAINING_ROWS = 100
+MIN_POSITIVE_EXAMPLES = 20
+MIN_NEGATIVE_EXAMPLES = 20
+
+# Warn when fewer than this fraction of the population is identified — under the v1
+# identified-only scope the anonymous remainder is silently excluded, so flag it.
+MIN_IDENTIFIED_FRACTION = 0.5
+
+# Cap the user_window CTE during live wizard estimates — sampled base rate is
+# unbiased for the same quantity the trainer computes unsampled.
+LIVE_ESTIMATE_SAMPLE_LIMIT = 5_000
+
+
+def inference_lookback_days(horizon_days: int) -> int:
+ # The window the scorer binds when it builds inference anchors (4x horizon, min 30),
+ # so the previewed population is the one that will actually be scored.
+ return max(30, horizon_days * 4)
+
+
+@frozen
+class ValidationWarning:
+ code: str
+ message: str
+ severity: str # "info" | "warning" | "error"
+
+
+@frozen
+class ValidationResult:
+ can_proceed: bool
+ requires_acknowledgement: bool
+ estimated_training_rows: Optional[int]
+ positive_count: Optional[int]
+ negative_count: Optional[int]
+ base_rate: Optional[float]
+ inference_population_size: Optional[int]
+ warnings: list[ValidationWarning] = field(default_factory=list)
+ error: Optional[str] = None
+
+
+def validate_pipeline_definition(
+ team: Team,
+ target_event: str,
+ horizon_days: int,
+ training_lookback_days: int,
+ training_population: dict[str, Any],
+ inference_population: dict[str, Any],
+ target_definition: dict[str, Any] | None = None,
+ user: User | None = None,
+) -> ValidationResult:
+ """
+ Validate a proposed pipeline definition against real team data.
+
+ Runs HogQL count queries to estimate volume, base rate, and catch common
+ mistakes before training is triggered. `user` is the person HogQL applies
+ access control for; without one the counts can be masked from data the
+ requester may read.
+ """
+ try:
+ return _run_validation(
+ 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,
+ )
+ except Exception as exc:
+ logger.exception("autoresearch_validation_error", team_id=team.pk, target_event=target_event)
+ return ValidationResult(
+ can_proceed=False,
+ requires_acknowledgement=False,
+ estimated_training_rows=None,
+ positive_count=None,
+ negative_count=None,
+ base_rate=None,
+ inference_population_size=None,
+ error=str(exc),
+ )
+
+
+def _run_validation(
+ *,
+ team: Team,
+ target_event: str,
+ horizon_days: int,
+ training_lookback_days: int,
+ training_population: dict[str, Any],
+ inference_population: dict[str, Any],
+ target_definition: dict[str, Any] | None = None,
+ user: User | None = None,
+) -> ValidationResult:
+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
+
+ # Headline eligible count — true number of users that would be labeled by the
+ # random-T0 labeler, no sampling. Used for the UI's "Training rows" metric and
+ # volume warnings.
+ eligible_sql, eligible_values = build_eligible_count_sql(
+ horizon_days=horizon_days,
+ lookback_days=training_lookback_days,
+ training_population=training_population,
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ )
+ eligible_rows = run_hogql_rows(team=team, query=HogQLQuery(query=eligible_sql, values=eligible_values), 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
+ total_users_all = 0
+ if eligible_rows:
+ row = eligible_rows[0]
+ total_users = int(row[0] or 0)
+ total_users_all = int(row[1] or 0) if len(row) > 1 else total_users
+
+ # Sampled random-T0 labeler — each user is assigned a deterministic random T0 in
+ # their history and labeled by whether target_event fires in [T0, T0 + horizon).
+ # Sampled at LIVE_ESTIMATE_SAMPLE_LIMIT for fast wizard feedback; the resulting
+ # base_rate is an unbiased estimator of the trainer's unsampled rate.
+ label_sql, label_values = build_random_t0_labeler_sql(
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ horizon_days=horizon_days,
+ lookback_days=training_lookback_days,
+ 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)
+ sampled_users = 0
+ sampled_positives = 0
+ if label_rows:
+ row = label_rows[0]
+ sampled_users = int(row[0] or 0)
+ sampled_positives = int(row[1] or 0)
+
+ base_rate = sampled_positives / sampled_users if sampled_users > 0 else 0.0
+ # Extrapolate sample-rate to the full eligible population for the headline counts.
+ 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
+ )
+ 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},
+ )
+ 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
+
+ warnings = _build_warnings(
+ total_users=total_users,
+ total_users_all=total_users_all,
+ positives=positives,
+ negatives=negatives,
+ base_rate=base_rate,
+ lookback_days=training_lookback_days,
+ target_event=target_event,
+ )
+ has_errors = any(w.severity == "error" for w in warnings)
+ has_hard_warnings = any(w.severity == "warning" for w in warnings)
+
+ return ValidationResult(
+ can_proceed=not has_errors,
+ requires_acknowledgement=has_hard_warnings and not has_errors,
+ estimated_training_rows=total_users,
+ positive_count=positives,
+ negative_count=negatives,
+ base_rate=base_rate,
+ inference_population_size=inference_size,
+ warnings=warnings,
+ )
+
+
+def _build_warnings(
+ *,
+ total_users: int,
+ total_users_all: int,
+ positives: int,
+ negatives: int,
+ base_rate: float,
+ lookback_days: int,
+ target_event: str,
+) -> list[ValidationWarning]:
+ warnings: list[ValidationWarning] = []
+
+ # Volume warnings
+ if total_users < MIN_TRAINING_ROWS:
+ warnings.append(
+ ValidationWarning(
+ code="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",
+ )
+ )
+ elif total_users < MIN_TRAINING_ROWS * 5:
+ warnings.append(
+ ValidationWarning(
+ code="moderate_volume",
+ message=f"{total_users} users found. The model may have limited accuracy with this volume.",
+ severity="warning",
+ )
+ )
+
+ # Mostly-anonymous population — under the v1 identified-only scope the anonymous
+ # remainder is excluded from training and scoring, which can shrink the population
+ # well below what the user expects. Warn so the exclusion is visible.
+ if IDENTIFIED_USERS_ONLY and total_users_all > 0:
+ identified_fraction = total_users / total_users_all
+ if identified_fraction < MIN_IDENTIFIED_FRACTION:
+ excluded = total_users_all - total_users
+ warnings.append(
+ ValidationWarning(
+ code="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.",
+ severity="warning",
+ )
+ )
+
+ if positives < MIN_POSITIVE_EXAMPLES:
+ warnings.append(
+ ValidationWarning(
+ code="low_positives",
+ message=f"Only {positives} users performed '{target_event}'. "
+ f"At least {MIN_POSITIVE_EXAMPLES} positive examples are needed.",
+ severity="error",
+ )
+ )
+
+ if negatives < MIN_NEGATIVE_EXAMPLES:
+ warnings.append(
+ ValidationWarning(
+ code="low_negatives",
+ message=f"Only {negatives} users did not perform '{target_event}'. "
+ f"At least {MIN_NEGATIVE_EXAMPLES} negative examples are needed.",
+ severity="error",
+ )
+ )
+
+ # Extreme imbalance
+ if total_users > 0 and base_rate < 0.01:
+ warnings.append(
+ ValidationWarning(
+ code="extreme_imbalance",
+ message=f"Base rate is {base_rate:.2%}. Very rare events need a larger population "
+ "for reliable calibration.",
+ severity="warning",
+ )
+ )
+ elif total_users > 0 and base_rate > 0.95:
+ warnings.append(
+ ValidationWarning(
+ code="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",
+ )
+ )
+
+ return warnings
diff --git a/products/autoresearch/backend/management/AGENTS.md b/products/autoresearch/backend/management/AGENTS.md
new file mode 100644
index 000000000000..25a3a8c28610
--- /dev/null
+++ b/products/autoresearch/backend/management/AGENTS.md
@@ -0,0 +1,62 @@
+# Management commands
+
+The headless entrypoints. Four commands cover the whole product lifecycle, and together they are how autoresearch is exercised end to end locally without a browser.
+
+This package landed with `autoresearch_validate` only. `autoresearch_train`, `autoresearch_score`, and `autoresearch_validate_online` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
+
+Every command calls the same functions the API and the Temporal activities call. They are thin wrappers, not a parallel implementation, and they should stay that way.
+
+**All of them bypass the `autoresearch` feature flag.** That is why local CLI testing works with no flag setup while the API and UI still need one.
+
+## The four commands
+
+- `autoresearch_train` — create a pipeline and/or launch training.
+ `--pipeline-id | --team-id --target --name --horizon --create --stub --user-id --iterations`
+ With `--create` it creates the pipeline first. With `--stub` it runs `../training/stub.py` (deterministic, free); without it, the real Claude agent runs in a sandbox and costs roughly a dollar.
+ **Use `--stub` for anything that isn't specifically testing the agent.**
+- `autoresearch_score` — load the champion, score the inference population, emit `autoresearch_prediction` events.
+ `--pipeline-id --dry-run --seed-fixture-bundle --prediction-date --backfill-days`
+ `--prediction-date` / `--backfill-days` backdate the emitted events, which is the only way to get matured predictions for online validation without waiting out the horizon.
+- `autoresearch_validate` — pre-flight target viability, before committing to a run.
+ `--team-id --target --horizon --user-id`
+ `--user-id` is the person HogQL applies access control for; without it the counts run fail-closed. Note there is no `--mode` flag. Note also that `autoresearch_train` does **not** call this, so a target that fails here still trains.
+- `autoresearch_validate_online` — realized performance for predictions whose horizon has elapsed.
+ `--pipeline-id --dry-run`
+
+## Running them locally
+
+Prefix with `CLICKHOUSE_DATABASE=posthog` and run inside the flox environment:
+
+```bash
+CLICKHOUSE_DATABASE=posthog flox activate -- bash -c \
+ "python manage.py autoresearch_train --create --team-id <TEAM> --target <EVENT> \
+ --name '<NAME>' --horizon 30 --user-id <UID> --stub"
+```
+
+The env var is needed because flox only sources `.env` on first activation, so the setting is not otherwise present for a one-shot command.
+
+## Things that bite
+
+- **`--stub` versus real is a money decision, not a speed one.** A real run launches a sandbox agent and spends LLM budget. Default to stub.
+- **The real-agent path needs more than an API key.** It runs in a Tasks sandbox, so it needs Tasks access and a working MCP server — if the sandbox agent cannot load the `autoresearch-*` MCP tools it will burn a full run doing nothing and fail with `"Agent recorded no iterations before the run ended."`
+- **Check the team id.** Demo data does not reliably live on team 1 or team 2; confirm before targeting.
+- **Pick a target with volume.** Conversion-shaped events are rare by nature. Engagement events give far more positives, and autoresearch only trains on identified users, so raw event counts overstate what is available.
+- **`autoresearch_score` on a fresh pipeline emits nothing** if there is no champion yet — train first.
+- **Backdated events vanish silently** when the team has `drop_events_older_than_seconds` set; ingestion drops them as too old.
+- A large `--backfill-days` run emits N × population events into Kafka in a tight loop and can knock over a local ingestion consumer. Prefer 10–15 days at a time.
+- Ad-hoc scripts that call `sync_execute` directly raise `UntaggedQueryError` — wrap with `tag_queries(product="autoresearch", ...)`. These commands already tag themselves.
+
+## Where the rest of the system meets this package
+
+- `autoresearch_train` → `../training/runner.py` (real) or `../training/stub.py` (`--stub`)
+- `autoresearch_score` → `../inference/scoring.py`
+- `autoresearch_validate` → `../dataset/validation.py`
+- `autoresearch_validate_online` → `../evaluation/online_validation.py`
+
+The same functions are reached on the scheduled path via `../temporal/workflows.py`, and on the HTTP path via `../presentation/views/views.py`.
+
+## When editing this flow
+
+- **Keep the commands thin.** Logic belongs in the package the command calls, so the scheduled path and the API path get it too. A behavior that only exists in a command will not exist in production.
+- Adding a flag that changes modeling behavior is a smell — it means the pipeline definition should carry it instead.
+- **If you add a command or change its flags, update this file to match.**
diff --git a/products/autoresearch/backend/management/CLAUDE.md b/products/autoresearch/backend/management/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/autoresearch/backend/management/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/autoresearch/backend/management/__init__.py b/products/autoresearch/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/autoresearch/backend/management/commands/__init__.py b/products/autoresearch/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/autoresearch/backend/management/commands/autoresearch_validate.py b/products/autoresearch/backend/management/commands/autoresearch_validate.py
new file mode 100644
index 000000000000..ad15155b285b
--- /dev/null
+++ b/products/autoresearch/backend/management/commands/autoresearch_validate.py
@@ -0,0 +1,105 @@
+"""
+Validate a proposed autoresearch pipeline definition against real team data.
+
+Usage:
+ python manage.py autoresearch_validate \\
+ --team-id 2 \\
+ --target '$pageview' \\
+ --horizon 7 \\
+ --user-id 1
+
+Prints volume estimates, base rate, and any warnings, and exits nonzero when the
+definition is rejected. The counts run under the given user's HogQL access control,
+as the API path does for the request user.
+"""
+
+from argparse import ArgumentParser, ArgumentTypeError
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.autoresearch.backend.dataset.validation import validate_pipeline_definition
+
+
+def _positive_int(value: str) -> int:
+ parsed = int(value)
+ if parsed < 1:
+ raise ArgumentTypeError(f"must be a positive integer, got {value}")
+ return parsed
+
+
+class Command(BaseCommand):
+ help = "Validate a pipeline definition (volume, base rate, warnings) without creating it."
+
+ def add_arguments(self, parser: ArgumentParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team ID to validate against.")
+ parser.add_argument("--target", required=True, help="Target event name, e.g. '$pageview'.")
+ parser.add_argument("--horizon", type=_positive_int, default=7, help="Prediction horizon in days (default: 7).")
+ parser.add_argument(
+ "--user-id",
+ type=int,
+ default=None,
+ help="User whose HogQL access control the counts run under. Without one HogQL fails closed.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id = options["team_id"]
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ raise CommandError(f"Team {team_id} not found.")
+
+ user: User | None = None
+ if options["user_id"] is not None:
+ # HogQL applies property restrictions for the user but does not check
+ # project membership, so an outsider must be refused here.
+ user = team.all_users_with_access().filter(pk=options["user_id"]).first()
+ if user is None:
+ raise CommandError(f"User {options['user_id']} not found or has no access to team {team_id}.")
+
+ self.stdout.write(f"\nValidating pipeline definition for team '{team.name}' (id={team_id})")
+ self.stdout.write(f" Target event : {options['target']}")
+ self.stdout.write(f" Horizon : {options['horizon']} days")
+ self.stdout.write("")
+
+ result = validate_pipeline_definition(
+ team=team,
+ target_event=options["target"],
+ horizon_days=options["horizon"],
+ training_lookback_days=180,
+ training_population={},
+ inference_population={},
+ user=user,
+ )
+
+ if result.error:
+ raise CommandError(f"Validation failed with error: {result.error}")
+
+ self.stdout.write("── Volume estimates ──────────────────────────────────")
+ self.stdout.write(f" Estimated training rows : {result.estimated_training_rows}")
+ self.stdout.write(f" Positive examples : {result.positive_count}")
+ self.stdout.write(f" Negative examples : {result.negative_count}")
+ self.stdout.write(
+ f" Base rate : {result.base_rate:.2%}"
+ if result.base_rate is not None
+ else " Base rate : n/a"
+ )
+ self.stdout.write(f" Inference population : {result.inference_population_size}")
+ self.stdout.write("")
+
+ if result.warnings:
+ self.stdout.write("── Warnings ──────────────────────────────────────────")
+ for w in result.warnings:
+ color = self.style.ERROR if w.severity == "error" else self.style.WARNING
+ self.stdout.write(color(f" [{w.severity.upper()}] {w.code}: {w.message}"))
+ self.stdout.write("")
+
+ if not result.can_proceed:
+ raise CommandError("Validation failed. Resolve the errors above before creating the pipeline.")
+ if result.requires_acknowledgement:
+ self.stdout.write(self.style.WARNING("✓ Can proceed, but the warnings above need acknowledgement."))
+ else:
+ self.stdout.write(self.style.SUCCESS("✓ Validation passed. The pipeline can be created."))
diff --git a/products/autoresearch/backend/management/test_autoresearch_validate.py b/products/autoresearch/backend/management/test_autoresearch_validate.py
new file mode 100644
index 000000000000..b9fab704365e
--- /dev/null
+++ b/products/autoresearch/backend/management/test_autoresearch_validate.py
@@ -0,0 +1,41 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from posthog.models.organization import Organization
+from posthog.models.user import User
+
+from products.autoresearch.backend.dataset.validation import ValidationResult
+
+
+class TestAutoresearchValidateCommand(BaseTest):
+ def test_user_without_team_access_is_refused_before_any_query(self) -> None:
+ outsider = User.objects.create_user(email="[email protected]", password="x", first_name="Out")
+ Organization.objects.create(name="Elsewhere").members.add(outsider)
+ with (
+ patch(
+ "products.autoresearch.backend.management.commands.autoresearch_validate.validate_pipeline_definition"
+ ) as validate,
+ self.assertRaises(CommandError),
+ ):
+ call_command("autoresearch_validate", team_id=self.team.pk, target="$pageview", user_id=outsider.pk)
+ validate.assert_not_called()
+
+ def test_member_is_passed_to_validation(self) -> None:
+ ok = ValidationResult(
+ can_proceed=True,
+ requires_acknowledgement=False,
+ estimated_training_rows=1000,
+ positive_count=100,
+ negative_count=900,
+ base_rate=0.1,
+ inference_population_size=1000,
+ )
+ with patch(
+ "products.autoresearch.backend.management.commands.autoresearch_validate.validate_pipeline_definition",
+ return_value=ok,
+ ) as validate:
+ call_command("autoresearch_validate", team_id=self.team.pk, target="$pageview", user_id=self.user.pk)
+ assert validate.call_args.kwargs["user"] == self.user