Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(autoresearch): roll back a champion whose features.sql cannot score (#111605)

posthog[bot]2a289c4dacbc
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 9a7132390a3f..d6753da1db9b 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -47,8 +47,9 @@ from ..models import (
AutoresearchSuggestion,
AutoresearchTrainingRun,
)
+from ..query import measure_queries
from ..training import artifacts as artifact_store
-from ..training.recipe_validation import RecipeValidationError, validate_feature_sql, validate_recipe
+from ..training.recipe_validation import RecipeValidationError, feature_sql_hints, validate_feature_sql, validate_recipe
from ..training.shadow_set import shadow_set_ids
from .contracts import (
ArtifactContent,
@@ -1257,12 +1258,14 @@ def materialize_features(
sandbox_id = _resolve_run_sandbox_id(training_run)
team = Team.objects.get(pk=team_id)
try:
- data = materialize_training_data(
- team=team,
- pipeline=training_run.pipeline,
- feature_sql=features_sql,
- user=user,
- anchor_ts=training_run.anchor_ts,
+ data, cost = measure_queries(
+ lambda: materialize_training_data(
+ team=team,
+ pipeline=training_run.pipeline,
+ feature_sql=features_sql,
+ user=user,
+ anchor_ts=training_run.anchor_ts,
+ )
)
except (SandboxInferenceError, RecipeValidationError) as exc:
raise AutoresearchConflict(f"Feature materialization failed: {exc}") from exc
@@ -1294,6 +1297,9 @@ def materialize_features(
n_holdout=len(data.holdout_rows),
n_features=len(data.feature_cols),
feature_cols=list(data.feature_cols),
+ elapsed_s=cost.elapsed_s,
+ rows_read=cost.rows_read,
+ hints=feature_sql_hints(features_sql),
)
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 2a7897cc2423..509634a1ba7d 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -431,3 +431,6 @@ class MaterializedFeatures:
n_holdout: int
n_features: int
feature_cols: list[str]
+ elapsed_s: float
+ rows_read: int
+ hints: list[str]
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 031a626bc563..b715312c58d6 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -12,6 +12,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
- `sandbox.py`
The current path. Runs the agent-authored bundle in a Tasks sandbox, split by run type because train and predict have genuinely different data contracts:
- `fit_champion_model()` — **train run**, called once at training completion. Materializes the _labeled_ training population, runs the bundle's `train.py`, runs `predict.py` once against the holdout features as a smoke test, and only then persists the fitted `model.pkl` next to the bundle. A bundle whose two scripts disagree fails here, not on the first cadence.
+ - `check_scorability()` — called once after the champion fit. Runs the anchor count and the feature query of a scoring run against today's inference anchors under `BATCH_QUERY`, with no sandbox, and returns their `QueryCost` (`measure_queries()` in `../query.py`). Promotion rolls back a champion that fails it or runs over its time budget.
- `score_via_sandbox()` — **predict run**, called every cadence. Loads the persisted `model.pkl`, materializes _only_ the inference population (cutoff at the start of the prediction date, no labels, no holdout, no fold), runs `predict.py`, and hands scores to the emitter. A missing `model.pkl` fails the run.
Both entry points validate the bundle's `features.sql` with `validate_feature_sql()` (plus no trailing `LIMIT`/`OFFSET`/`SETTINGS`) before any query runs, and run every HogQL query as the pipeline's creator (`_resolve_acting_user()`, or the explicit `user` a management command passes), with `CALCULATE_BLOCKING_ALWAYS` so a cadence never reuses a cached population, and with `LABELER_QUERY_MODIFIERS`, so `person_id` resolves the same way in the anchors and the feature SQL, and a `person.*` column in feature SQL resolves through the persons table. The anchor SQL itself reads identity from `raw_persons`, not from `person.*`.
@@ -39,6 +40,7 @@ Every HogQL query goes through `run_hogql()` in `../query.py` with a `QueryConte
| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------- |
| Scoring from `activity_run_inference` (sweep and manual `/score`), both routes, with their anchor and population counts | `BATCH_QUERY` | `QUERY_ASYNC` (`HOGQL_INCREASED_MAX_EXECUTION_TIME`, 600 s), `OFFLINE` |
| Online validation from `activity_run_validation` | `BATCH_QUERY` | `QUERY_ASYNC`, `OFFLINE` |
+| `check_scorability()` after the champion fit at training completion | `BATCH_QUERY` | `QUERY_ASYNC`, `OFFLINE` |
| `fit_champion_model()` at training completion, `materialize-features`, `/validate`, `/validate_online` | `INTERACTIVE_QUERY` (the default) | `QUERY` (60 s), `DEFAULT` |
| Management commands | `INTERACTIVE_QUERY` (the default) | `QUERY`, `DEFAULT` |
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 9bdc3673cc64..5e6298fedee1 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -42,6 +42,7 @@ import math
import base64
import binascii
from dataclasses import field
+from datetime import UTC, datetime
from decimal import Decimal
from typing import Any, Protocol
@@ -75,7 +76,14 @@ from products.autoresearch.backend.dataset.labeling import (
rolling_selection,
)
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
-from products.autoresearch.backend.query import INTERACTIVE_QUERY, QueryContext, run_hogql
+from products.autoresearch.backend.query import (
+ BATCH_QUERY,
+ INTERACTIVE_QUERY,
+ QueryContext,
+ QueryCost,
+ measure_queries,
+ run_hogql,
+)
from products.autoresearch.backend.training.artifacts import (
MAX_ARTIFACT_BYTES,
ArtifactBundle,
@@ -314,6 +322,33 @@ def score_via_sandbox(
)
+def check_scorability(
+ *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User | None = None
+) -> QueryCost:
+ """
+ Run ``feature_sql`` against today's inference anchors under the limits a scoring run has,
+ and return what the queries cost. It runs the anchor count and the feature query the
+ scoring cadence runs, but no sandbox, so a champion whose SQL cannot score is found right
+ after its fit and not on every cadence after it.
+
+ Raises SandboxInferenceError when either query fails or the rows do not key the anchors.
+ """
+ acting_user = _resolve_acting_user(team=team, pipeline=pipeline, user=user)
+ today = django_timezone.now().date()
+ cutoff_ts = int(datetime(today.year, today.month, today.day, tzinfo=UTC).timestamp())
+ _, cost = measure_queries(
+ lambda: _materialize_score_data(
+ team=team,
+ pipeline=pipeline,
+ feature_sql=feature_sql,
+ cutoff_ts=cutoff_ts,
+ user=acting_user,
+ query_context=BATCH_QUERY,
+ )
+ )
+ return cost
+
+
# ── Guards on the bundle and the acting user ──────────────────────────────────────
diff --git a/products/autoresearch/backend/inference/test_materialize_features.py b/products/autoresearch/backend/inference/test_materialize_features.py
index a4e3e82bb7bf..441fde9d26ec 100644
--- a/products/autoresearch/backend/inference/test_materialize_features.py
+++ b/products/autoresearch/backend/inference/test_materialize_features.py
@@ -140,6 +140,7 @@ class TestMaterializeFeatures(TeamScopedTestMixin, APIBaseTest):
assert body["n_holdout"] == 2
assert body["n_features"] == 2
assert body["feature_cols"] == ["pv", "uploads"]
+ assert (body["rows_read"], body["hints"]) == (0, [])
# All four parquet files land in one per-request directory under the framework-controlled base.
directory = body["train_features_path"].rsplit("/", 1)[0]
assert directory.startswith("/tmp/workspace/autoresearch/data/")
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index acc892ddf2b8..e8be41cc1ea3 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1593,6 +1593,20 @@ class MaterializeFeaturesResponseSerializer(serializers.Serializer):
child=serializers.CharField(),
help_text="The numeric feature column names (excludes distinct_id, __label, __fold).",
)
+ elapsed_s = serializers.FloatField(
+ help_text=(
+ "Seconds the server spent on the queries that materialized the matrix. Scoring runs features_sql "
+ "over the whole inference population on every cadence, so a slow query here is slow there too."
+ )
+ )
+ rows_read = serializers.IntegerField(help_text="Rows ClickHouse read to materialize the matrix.")
+ hints = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "Advice on the cost of features_sql. A hint does not block the materialization or the upload, "
+ "but a champion whose features.sql cannot score today's population in time is not promoted."
+ ),
+ )
# ── Artifact bundle serializers ─────────────────────────────────────────────
diff --git a/products/autoresearch/backend/query.py b/products/autoresearch/backend/query.py
index 9154faaef4d0..c9281a418e1b 100644
--- a/products/autoresearch/backend/query.py
+++ b/products/autoresearch/backend/query.py
@@ -1,8 +1,11 @@
-from typing import Any
+from collections.abc import Callable
+from time import perf_counter
+from typing import Any, TypeVar
from posthog.schema import CacheMissResponse, HogQLQuery, QueryStatusResponse
from posthog.hogql.constants import LimitContext
+from posthog.hogql.query_stats import query_stats_scope
from posthog.clickhouse.workload import Workload
from posthog.dataclasses import frozen
@@ -11,6 +14,8 @@ from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.team.team import Team
from posthog.models.user import User
+T = TypeVar("T")
+
class AutoresearchQueryError(Exception):
pass
@@ -32,6 +37,28 @@ INTERACTIVE_QUERY = QueryContext(limit_context=LimitContext.QUERY, workload=Work
BATCH_QUERY = QueryContext(limit_context=LimitContext.QUERY_ASYNC, workload=Workload.OFFLINE)
+@frozen
+class QueryCost:
+ """What the ClickHouse queries of one call cost: wall-clock seconds and the rows they read."""
+
+ elapsed_s: float
+ rows_read: int
+
+
+def measure_queries(call: Callable[[], T]) -> tuple[T, QueryCost]:
+ """Run ``call`` and return its result with the cost of the ClickHouse queries it ran.
+
+ A scope that is already open (a query runner around this call) collects the same queries,
+ so the cost is the difference of its totals across the call.
+ """
+ start = perf_counter()
+ with query_stats_scope() as stats:
+ rows_before = stats.rows_read
+ result = call()
+ rows_read = stats.rows_read - rows_before
+ return result, QueryCost(elapsed_s=round(perf_counter() - start, 3), rows_read=rows_read)
+
+
@frozen
class HogQLResult:
columns: list[str]
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 5dca3543d1bc..05d8ea217906 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -17,6 +17,8 @@ The other half is `../inference/`, which consumes what this package produces and
The brief's worked `features.sql` reads events through a pre-filtered subquery (the event names the features use, the anchor persons, and the anchors' widest window) before it joins, because ClickHouse builds the hash table from the right side of a join and a direct events join reads the whole team's events.
The brief also states the inference cutoff: the start of the prediction date in UTC (`ScoringWindow` in `../inference/scoring.py`), not `now()`.
The brief's cost guidance is advice only. Cost does not enter champion selection, so the brief does not tell the agent to trade AUC for a cheaper query.
+ For a person column that events do not carry, the brief recommends `raw_persons` in a subquery filtered with `id IN (SELECT person_id FROM {anchors})`, never `LEFT JOIN persons`, because the persons table dedupes every person of the team before any filter applies.
+ `feature_sql_hints()` in `recipe_validation.py` returns a non-blocking hint when a query reads `persons` or `raw_persons` in a SELECT whose `WHERE` does not refer to `{anchors}`. The `materialize-features` response carries the hints, with the `elapsed_s` and `rows_read` of the materialization.
The agent drives the rest _itself_ through the `autoresearch-*` MCP tools: it records each iteration, uploads the bundle, and calls complete. Nothing polls it.
- `stub.py`
`run_stub_training()` — a hand-authored champion recipe with universal engagement features (event counts, distinct event types, days since first seen) that apply to any team and any target.
@@ -32,8 +34,12 @@ The other half is `../inference/`, which consumes what this package produces and
The bundle is written once per run, so a losing iteration can overwrite it: the uploaded `features.sql` must match the `feature_sql` recorded by the selected iteration, whitespace aside, or promotion raises rather than publishing a champion whose recipe and score describe other code.
`complete_training_run()` reads the bundle and enters the run's `team_scope()` before it opens the transaction, because the `TaskRun` safety net calls it from a worker thread with no request scope, and object-storage calls must not run under the row lock.
The agent's `report_notebook_short_id` goes into the run summary only if that notebook exists in the run's team. A bad id or a failed check stores an empty value and never fails completion.
- A promoted bundle-backed model is fitted. A bundle-backed challenger is fitted only when it enters the shadow set (see `shadow_set.py`). The fit runs after commit, and a failed fit only logs: it never changes the completion result.
- A successful fit sets `metrics.model_fitted`. A challenger without it stays out of the shadow set.
+ A promoted bundle-backed model is fitted. A bundle-backed challenger is fitted only when it enters the shadow set (see `shadow_set.py`). The fit runs after commit and never changes the completion result.
+ A successful challenger fit sets `metrics.model_fitted`, and a failed one only logs. A challenger without `model_fitted` stays out of the shadow set.
+ After a champion fit, `check_scorability()` runs the bundle's `features.sql` against today's inference anchors under `BATCH_QUERY`. A passing check records `scorability_elapsed_s` and `scorability_rows_read` in the model metrics and sets `model_fitted`.
+ A failed fit, a failed check, or a check above `SCORABILITY_TIME_BUDGET_S` (half the batch query limit) rolls the promotion back under the pipeline lock: the candidate becomes a challenger with `not_promoted_reason` in its metrics, and the champion it archived comes back. A first champion that rolls back puts the pipeline back in the status it had before promotion. The rolled-back candidate has no `model_fitted`, so it never enters the shadow set.
+ The rollback changes nothing when the candidate is no longer the champion. A scoring run that started with the candidate fails in `_require_still_champion()` before it emits.
+ A champion that is already unscorable is not repaired here, and a recipe-only champion is not checked.
- `shadow_set.py`
`shadow_set(pipeline)` computes the models worth scoring side by side. Nothing stores the set.
It holds the champion, the previous champion (the newest archived bundle-backed row with `promoted_at` set), and up to `SHADOW_CHALLENGER_LIMIT` (3) fitted bundle-backed challengers. No two members share a `recipe_hash`.
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index 6ae39c9b9f04..8ccd807bfafc 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -24,9 +24,11 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.visitor import clear_locations
from posthog.models.scoping import team_scope
+from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from products.autoresearch.backend.inference.sandbox import (
SandboxInferenceError,
+ check_scorability,
fit_champion_model,
validate_runnable_feature_sql,
)
@@ -37,6 +39,7 @@ from products.autoresearch.backend.models import (
AutoresearchPipeline,
AutoresearchTrainingRun,
)
+from products.autoresearch.backend.query import QueryCost
from products.autoresearch.backend.training import artifacts
from products.autoresearch.backend.training.recipe_validation import RecipeValidationError, validate_model_class
from products.autoresearch.backend.training.shadow_set import FITTED_METRIC_KEY, shadow_set
@@ -48,6 +51,10 @@ logger = structlog.get_logger(__name__)
# before it is promoted — guards against thrashing on noise-level differences.
CHAMPION_PROMOTION_MARGIN = 0.005
+# Scoring runs the same queries under the batch query limit. A champion that needs half of that
+# limit today has little room left before population growth makes every cadence fail.
+SCORABILITY_TIME_BUDGET_S = HOGQL_INCREASED_MAX_EXECUTION_TIME / 2
+
class PromotionError(ValueError):
"""Raised when completion cannot select a valid champion candidate."""
@@ -362,39 +369,180 @@ def _activate_pipeline(pipeline: AutoresearchPipeline) -> None:
def _schedule_model_fit(
- *, pipeline: AutoresearchPipeline, prefix: str, training_run: AutoresearchTrainingRun, model_id: str
+ *,
+ pipeline: AutoresearchPipeline,
+ bundle: artifacts.ArtifactBundle,
+ prefix: str,
+ training_run: AutoresearchTrainingRun,
+ model_id: str,
+ promoted: bool,
+ previous_champion_id: str | None,
+ previous_status: str | None,
) -> None:
"""The train run produces the serving artifact: fit the model and persist model.pkl so
predict runs are pure inference. Deferred to on_commit, because the sandbox and the
object-storage write are side effects that must not run inside the atomic block, and the
- fit only makes sense once the row is durably committed. A failed champion fit leaves the
- champion without a model.pkl, and every scoring run then fails until a later promotion
- fits one. A failed challenger fit keeps the challenger out of the shadow set.
- The fit labels at the run's anchor instant, so it sees the anchor set the agent scored."""
+ fit only makes sense once the row is durably committed. A failed challenger fit keeps the
+ challenger out of the shadow set. The fit labels at the run's anchor instant, so it sees
+ the anchor set the agent scored.
+
+ After a champion fit, the bundle's features.sql runs against today's inference anchors under
+ the scoring limits. A failed fit, a failed check, or a check over ``SCORABILITY_TIME_BUDGET_S``
+ rolls the promotion back, because a champion that cannot score fails every cadence and no
+ other path replaces it."""
training_run_id = str(training_run.id)
anchor_ts = training_run.anchor_ts
+ def roll_back(reason: str, cost: QueryCost | None = None) -> None:
+ _roll_back_promotion(
+ pipeline=pipeline,
+ training_run_id=training_run_id,
+ model_id=model_id,
+ previous_champion_id=previous_champion_id,
+ previous_status=previous_status,
+ reason=reason,
+ cost=cost,
+ )
+
def _fit_after_commit() -> None:
# Every failure is caught, not only SandboxInferenceError: the run is already
# committed, so raising here would report a failed completion for a finished run
# that a retry can only answer with its no-op.
try:
- fit_champion_model(
- team=pipeline.team, pipeline=pipeline, prefix=prefix, anchor_ts=anchor_ts, model_id=model_id
- )
- _mark_fitted(team_id=pipeline.team_id, model_id=model_id)
+ try:
+ fit_champion_model(
+ team=pipeline.team,
+ pipeline=pipeline,
+ prefix=prefix,
+ bundle=bundle,
+ anchor_ts=anchor_ts,
+ model_id=model_id,
+ )
+ except Exception as exc:
+ logger.exception("autoresearch_model_fit_failed", training_run_id=training_run_id, prefix=prefix)
+ if promoted:
+ roll_back(f"The champion fit failed: {exc}")
+ return
+ if not promoted:
+ _mark_fitted(team_id=pipeline.team_id, model_id=model_id)
+ return
+ try:
+ cost = check_scorability(team=pipeline.team, pipeline=pipeline, feature_sql=bundle.features_sql)
+ except Exception as exc:
+ logger.exception("autoresearch_champion_unscorable", training_run_id=training_run_id, prefix=prefix)
+ roll_back(f"features.sql failed against today's inference anchors: {exc}")
+ return
+ if cost.elapsed_s > SCORABILITY_TIME_BUDGET_S:
+ roll_back(
+ f"features.sql took {cost.elapsed_s:.0f}s against today's inference anchors, "
+ f"above the {SCORABILITY_TIME_BUDGET_S:.0f}s budget for a scoring run",
+ cost,
+ )
+ return
+ _mark_fitted(team_id=pipeline.team_id, model_id=model_id, cost=cost)
except Exception:
logger.exception("autoresearch_model_fit_failed", training_run_id=training_run_id, prefix=prefix)
transaction.on_commit(_fit_after_commit)
-def _mark_fitted(*, team_id: int, model_id: str) -> None:
- model = AutoresearchModel.objects.for_team(team_id).filter(pk=model_id).first()
- if model is None:
- return
- model.metrics = {**(model.metrics or {}), FITTED_METRIC_KEY: True}
- model.save(update_fields=["metrics", "updated_at"])
+def _scorability_metrics(cost: QueryCost) -> dict[str, Any]:
+ return {
+ "scorability_elapsed_s": cost.elapsed_s,
+ "scorability_rows_read": cost.rows_read,
+ }
+
+
+def _mark_fitted(*, team_id: int, model_id: str, cost: QueryCost | None = None) -> None:
+ """A rolled-back champion is never marked, so it stays out of the shadow set."""
+ with team_scope(team_id), transaction.atomic():
+ model = AutoresearchModel.objects.for_team(team_id).select_for_update().filter(pk=model_id).first()
+ if model is None:
+ return
+ model.metrics = {
+ **(model.metrics or {}),
+ **(_scorability_metrics(cost) if cost else {}),
+ FITTED_METRIC_KEY: True,
+ }
+ model.save(update_fields=["metrics", "updated_at"])
+ if cost is not None:
+ logger.info("autoresearch_champion_scorable", model_id=model_id, **_scorability_metrics(cost))
+
+
+def _roll_back_promotion(
+ *,
+ pipeline: AutoresearchPipeline,
+ training_run_id: str,
+ model_id: str,
+ previous_champion_id: str | None,
+ previous_status: str | None,
+ reason: str,
+ cost: QueryCost | None,
+) -> None:
+ """
+ Demote the candidate to a challenger and bring back the champion it replaced.
+
+ The pipeline row lock serializes this with a promotion of a later run. A candidate that is
+ no longer the champion was already replaced, so nothing changes. A scoring run that started
+ with the candidate fails in ``_require_still_champion()`` before it emits.
+ """
+ team_id = pipeline.team_id
+ with team_scope(team_id), transaction.atomic():
+ locked = AutoresearchPipeline.objects.for_team(team_id).select_for_update(no_key=True).get(pk=pipeline.pk)
+ candidate = (
+ AutoresearchModel.objects.for_team(team_id)
+ .select_for_update()
+ .filter(pk=model_id, pipeline=locked, role=AutoresearchModel.Role.CHAMPION)
+ .first()
+ )
+ if candidate is None:
+ logger.warning("autoresearch_champion_rollback_superseded", pipeline_id=str(pipeline.pk), model_id=model_id)
+ return
+ candidate.role = AutoresearchModel.Role.CHALLENGER
+ candidate.promoted_at = None
+ candidate.metrics = {
+ **(candidate.metrics or {}),
+ **(_scorability_metrics(cost) if cost else {}),
+ "not_promoted_reason": reason,
+ }
+ candidate.save(update_fields=["role", "promoted_at", "metrics"])
+
+ restored = None
+ if previous_champion_id is not None:
+ restored = (
+ AutoresearchModel.objects.for_team(team_id)
+ .select_for_update()
+ .filter(pk=previous_champion_id, pipeline=locked, role=AutoresearchModel.Role.ARCHIVED)
+ .first()
+ )
+ if restored is not None:
+ restored.role = AutoresearchModel.Role.CHAMPION
+ restored.archived_at = None
+ restored.save(update_fields=["role", "archived_at"])
+ elif previous_status is not None and locked.status == AutoresearchPipeline.Status.RUNNING:
+ # The candidate was the first champion and made the pipeline live. With no champion
+ # the daily sweep fails every cadence, so the pipeline goes back to waiting for one.
+ locked.status = previous_status
+ locked.save(update_fields=["status", "updated_at"])
+
+ training_run = (
+ AutoresearchTrainingRun.objects.for_team(team_id).select_for_update().filter(pk=training_run_id).first()
+ )
+ if training_run is not None and training_run.summary:
+ # The next run reads this summary as the champion it has to beat.
+ training_run.summary = {
+ **training_run.summary,
+ "champion_promoted": False,
+ "champion_model_class": str((restored.model_recipe or {}).get("model_class", "")) if restored else "",
+ }
+ training_run.save(update_fields=["summary"])
+ logger.warning(
+ "autoresearch_champion_rolled_back",
+ pipeline_id=str(pipeline.pk),
+ model_id=model_id,
+ restored_model_id=str(restored.pk) if restored else None,
+ reason=reason,
+ )
@transaction.atomic
@@ -452,6 +600,8 @@ def _finalize_under_lock(
best_score = best.holdout_score
candidate_score = best.holdout_score or 0.0
+ # The pipeline lock serializes this promotion with the rollback of an unscorable champion.
+ AutoresearchPipeline.objects.select_for_update(no_key=True).get(pk=pipeline.pk)
current = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()
is_cold_start = current is None
# A stub champion's score is a fixed placeholder, not a measurement, so any trained candidate replaces it.
@@ -507,15 +657,23 @@ def _finalize_under_lock(
)
training_run.save(update_fields=["status", "iteration_count", "best_holdout_score", "summary", "completed_at"])
+ status_before = pipeline.status
if promoted:
_activate_pipeline(pipeline)
# A challenger is fitted only when it enters the shadow set, because nothing else loads
# its model.pkl.
- if artifact_prefix and (
+ if bundle is not None and (
promoted or any(member.pk == model.pk for member in shadow_set(pipeline, now=now, pending_fit=model.pk))
):
_schedule_model_fit(
- pipeline=pipeline, prefix=artifact_prefix, training_run=training_run, model_id=str(model.pk)
+ pipeline=pipeline,
+ bundle=bundle,
+ prefix=artifact_prefix,
+ training_run=training_run,
+ model_id=str(model.pk),
+ promoted=promoted,
+ previous_champion_id=str(current.pk) if promoted and current is not None else None,
+ previous_status=status_before if status_before != pipeline.status else None,
)
return {
diff --git a/products/autoresearch/backend/training/recipe_validation.py b/products/autoresearch/backend/training/recipe_validation.py
index 8b2e89d7cf24..df325eb8e08f 100644
--- a/products/autoresearch/backend/training/recipe_validation.py
+++ b/products/autoresearch/backend/training/recipe_validation.py
@@ -53,6 +53,9 @@ _TRAINING_CTE_NAMES: frozenset[str] = frozenset({"user_window", "user_t0", "labe
# The training wrapper appends these columns to the feature rows, so a feature query that emits
# them makes the label lookup ambiguous.
_RESERVED_OUTPUT_NAMES: frozenset[str] = frozenset({"__label", "__fold"})
+# Person tables. The HogQL persons table dedupes every person of the team before any filter
+# applies, and raw_persons without a filter reads every version of every person.
+_PERSON_TABLES: frozenset[str] = frozenset({"persons", "raw_persons"})
class RecipeValidationError(ValueError):
@@ -104,6 +107,64 @@ def validate_feature_sql(feature_sql: str) -> None:
)
+def feature_sql_hints(feature_sql: str) -> list[str]:
+ """
+ Advice on what makes ``feature_sql`` expensive at scoring. A hint never blocks: the query is
+ valid, but it can run past the scoring time limit on a large team.
+
+ Feature SQL that does not parse gets no hints; ``validate_feature_sql`` reports it.
+ """
+ try:
+ node = parse_select(feature_sql)
+ except Exception:
+ return []
+ visitor = _UnfilteredPersonReads()
+ visitor.visit(node)
+ return [
+ f"feature_sql reads {table} without filtering it to the anchor persons, so the query reads every "
+ f"person of the team. Read raw_persons in a subquery with WHERE id IN (SELECT person_id FROM "
+ "{anchors}), and take each person's latest version with argMax(..., version)."
+ for table in sorted(visitor.tables)
+ ]
+
+
+class _UnfilteredPersonReads(TraversingVisitor):
+ """Person tables read by a SELECT whose WHERE or PREWHERE does not refer to ``{anchors}``."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.tables: set[str] = set()
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ join = node.select_from
+ while join is not None:
+ table = join.table
+ if isinstance(table, ast.Field) and len(table.chain) == 1:
+ name = str(table.chain[0]).lower()
+ if name in _PERSON_TABLES and not (_reads_anchors(node.where) or _reads_anchors(node.prewhere)):
+ self.tables.add(name)
+ join = join.next_join
+ super().visit_select_query(node)
+
+
+class _AnchorsReads(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_placeholder(self, node: ast.Placeholder) -> None:
+ if _is_anchors_placeholder(node):
+ self.found = True
+
+
+def _reads_anchors(node: ast.Expr | None) -> bool:
+ if node is None:
+ return False
+ visitor = _AnchorsReads()
+ visitor.visit(node)
+ return visitor.found
+
+
class _WallClockReads(TraversingVisitor):
def __init__(self) -> None:
super().__init__()
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index 96ed354739cd..a3678c18b4c2 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -431,6 +431,16 @@ def build_agent_description(
the latest value before the cutoff (for example `argMax(e.plan, e.timestamp)` over the joined
events). `person.properties.*` and `LEFT JOIN persons` both join the persons table, which is
slow on large teams, and return current values, which leak the label window at training.
+ - If you need a column that events do not carry, such as `created_at`, never `LEFT JOIN persons`.
+ The persons table dedupes every person of the team before any filter applies. Read
+ `raw_persons` in a subquery filtered to the anchor persons, and take each person's latest version:
+ `LEFT JOIN (SELECT id, argMax(created_at, version) AS created_at FROM raw_persons
+ WHERE id IN (SELECT person_id FROM {{anchors}}) GROUP BY id) p ON p.id = a.person_id`.
+ The materialize response returns a hint when a query reads a person table without that filter.
+ - The materialize response also returns `elapsed_s` and `rows_read`. After
+ promotion the backend runs your `features.sql` against today's inference population under
+ the scoring limits. If it fails, or takes more than half of the scoring time limit, the model
+ is not promoted and the previous champion keeps serving.
- Cost does not change which iteration wins, so keep each hypothesis cheap from the start.
### Step 3 — Materialize features, then fit and evaluate (in your sandbox)
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
index 1d1bcfc1dc1a..44dccd192d20 100644
--- a/products/autoresearch/backend/training/test_promotion.py
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -14,15 +14,21 @@ from posthog.models.scoping import unscoped
from posthog.models.team import Team
from posthog.storage.object_storage import ObjectStorageError
+from products.autoresearch.backend.inference.sandbox import SandboxInferenceError
from products.autoresearch.backend.models import (
AutoresearchIteration,
AutoresearchModel,
AutoresearchPipeline,
AutoresearchTrainingRun,
)
+from products.autoresearch.backend.query import QueryCost
from products.autoresearch.backend.testing import TeamScopedTestMixin
from products.autoresearch.backend.training.artifacts import ArtifactBundle, InvalidArtifactContent, PartialBundle
-from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run
+from products.autoresearch.backend.training.promotion import (
+ SCORABILITY_TIME_BUDGET_S,
+ PromotionError,
+ complete_training_run,
+)
from products.autoresearch.backend.training.shadow_set import shadow_set
from products.autoresearch.backend.training.stub import run_stub_training
from products.notebooks.backend.facade import api as notebooks_facade
@@ -387,32 +393,89 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
self._iteration(run, number=0, holdout=0.8)
bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
- with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
- with patch("products.autoresearch.backend.training.promotion.fit_champion_model") as fit:
- with self.captureOnCommitCallbacks(execute=True):
- complete_training_run(run)
+ cost = QueryCost(elapsed_s=12.5, rows_read=1000)
+ with (
+ patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle),
+ patch("products.autoresearch.backend.training.promotion.fit_champion_model") as fit,
+ patch("products.autoresearch.backend.training.promotion.check_scorability", return_value=cost),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ complete_training_run(run)
assert run.started_at is not None
assert fit.call_args.kwargs["anchor_ts"] == int(run.started_at.timestamp())
+ metrics = self._champion().metrics
+ assert (
+ metrics["scorability_elapsed_s"],
+ metrics["scorability_rows_read"],
+ ) == (12.5, 1000)
- def test_a_failed_champion_fit_does_not_fail_a_committed_completion(self):
- run = self._run()
- self._iteration(run, number=0, holdout=0.8)
+ @parameterized.expand(
+ [
+ # write_model raises this, and it is not a SandboxInferenceError.
+ ("fit_fails", ObjectStorageError("object storage unavailable"), None, "fit failed"),
+ ("check_fails", None, SandboxInferenceError("Feature query failed: timeout"), "failed against"),
+ (
+ "check_over_budget",
+ None,
+ QueryCost(elapsed_s=SCORABILITY_TIME_BUDGET_S + 1, rows_read=1),
+ "budget",
+ ),
+ ]
+ )
+ def test_an_unscorable_champion_rolls_back_to_the_previous_one(self, _name, fit_error, check_result, reason):
+ first = self._run()
+ self._iteration(first, number=0, holdout=0.7)
+ complete_training_run(first)
+ previous = self._champion()
+ second = self._run()
+ self._iteration(second, number=0, holdout=0.9)
bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
- with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
- with patch(
- "products.autoresearch.backend.training.promotion.fit_champion_model",
- # write_model raises this, and it is not a SandboxInferenceError. The run is
- # already committed, so it must not reach the caller as a failed completion.
- side_effect=ObjectStorageError("object storage unavailable"),
- ):
- with self.captureOnCommitCallbacks(execute=True):
- result = complete_training_run(run)
+ check = {"side_effect": check_result} if isinstance(check_result, Exception) else {"return_value": check_result}
+ with (
+ patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle),
+ patch("products.autoresearch.backend.training.promotion.fit_champion_model", side_effect=fit_error),
+ patch("products.autoresearch.backend.training.promotion.check_scorability", **check),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = complete_training_run(second)
+ # The run is already committed, so the rollback must not reach the caller as a failed completion.
assert result["promoted"] is True
- run.refresh_from_db()
- assert run.status == AutoresearchTrainingRun.Status.COMPLETED
+ second.refresh_from_db()
+ assert second.status == AutoresearchTrainingRun.Status.COMPLETED
+ assert second.summary["champion_promoted"] is False
+ assert self._champion().pk == previous.pk
+ candidate = AutoresearchModel.objects.for_team(self.team.id).get(pk=result["model_id"])
+ assert candidate.role == AutoresearchModel.Role.CHALLENGER
+ assert reason in candidate.metrics["not_promoted_reason"]
+ # A shadow set member is scored every cadence, so a candidate that cannot score must stay out.
+ assert result["model_id"] not in {str(m.pk) for m in shadow_set(self.pipeline)}
+
+ def test_an_unscorable_first_champion_returns_the_pipeline_to_bootstrapping(self):
+ self.pipeline.status = AutoresearchPipeline.Status.BOOTSTRAPPING
+ self.pipeline.save(update_fields=["status"])
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
+ with (
+ patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle),
+ patch("products.autoresearch.backend.training.promotion.fit_champion_model"),
+ patch(
+ "products.autoresearch.backend.training.promotion.check_scorability",
+ side_effect=SandboxInferenceError("Feature query failed"),
+ ),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ complete_training_run(run)
+
+ # A live pipeline with no champion would fail every daily sweep.
+ self.pipeline.refresh_from_db()
+ assert self.pipeline.status == AutoresearchPipeline.Status.BOOTSTRAPPING
+ assert not AutoresearchModel.objects.filter(
+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION
+ ).exists()
def test_model_recipe_hash_identifies_the_stored_recipe(self):
run = self._run()
diff --git a/products/autoresearch/backend/training/test_recipe_validation.py b/products/autoresearch/backend/training/test_recipe_validation.py
index 737b13d47adb..a2763c30141e 100644
--- a/products/autoresearch/backend/training/test_recipe_validation.py
+++ b/products/autoresearch/backend/training/test_recipe_validation.py
@@ -8,6 +8,7 @@ from posthog.hogql.parser import parse_select
from products.autoresearch.backend.dataset.labeling import build_training_features_sql
from products.autoresearch.backend.training.recipe_validation import (
RecipeValidationError,
+ feature_sql_hints,
validate_feature_sql,
validate_recipe,
validate_unique_distinct_ids,
@@ -17,6 +18,34 @@ ANCHORED = "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GRO
class TestRecipeValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "left_join_persons",
+ "SELECT a.person_id AS distinct_id, p.created_at AS created FROM {anchors} a "
+ "LEFT JOIN persons p ON p.id = a.person_id",
+ ["persons"],
+ ),
+ (
+ "unfiltered_raw_persons_subquery",
+ "SELECT a.person_id AS distinct_id, p.c AS created FROM {anchors} a LEFT JOIN "
+ "(SELECT id, argMax(created_at, version) AS c FROM raw_persons GROUP BY id) p ON p.id = a.person_id",
+ ["raw_persons"],
+ ),
+ (
+ "raw_persons_filtered_to_the_anchors",
+ "SELECT a.person_id AS distinct_id, p.c AS created FROM {anchors} a LEFT JOIN "
+ "(SELECT id, argMax(created_at, version) AS c FROM raw_persons "
+ "WHERE id IN (SELECT person_id FROM {anchors}) GROUP BY id) p ON p.id = a.person_id",
+ [],
+ ),
+ ("no_person_table", ANCHORED, []),
+ ]
+ )
+ def test_hints_flag_person_tables_read_without_an_anchor_filter(self, _name, sql, tables):
+ hints = feature_sql_hints(sql)
+ assert [hint.split(" ")[2] for hint in hints] == tables
+
@parameterized.expand(
[
("absent", "SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id"),
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 2b981b253e30..231f2c5d9e8a 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -1122,6 +1122,12 @@ export interface MaterializeFeaturesResponseApi {
n_features: number
/** The numeric feature column names (excludes distinct_id, __label, __fold). */
feature_cols: string[]
+ /** Seconds the server spent on the queries that materialized the matrix. Scoring runs features_sql over the whole inference population on every cadence, so a slow query here is slow there too. */
+ elapsed_s: number
+ /** Rows ClickHouse read to materialize the matrix. */
+ rows_read: number
+ /** Advice on the cost of features_sql. A hint does not block the materialization or the upload, but a champion whose features.sql cannot score today's population in time is not promoted. */
+ hints: string[]
}
/**
diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yaml
index 125b023a7ec9..b5152e9a60bc 100644
--- a/products/autoresearch/mcp/tools.yaml
+++ b/products/autoresearch/mcp/tools.yaml
@@ -103,8 +103,11 @@ tools:
train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list —
the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the
returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it
- whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog
- sandbox; an agent training outside PostHog pulls its data with execute-sql instead.
+ whenever you change features.sql. Also returns what the feature query cost (elapsed_s and rows_read) and
+ hints about features.sql shapes that scale badly. A promoted model must score its inference population under
+ batch limits before it serves, so a slow or heavy query here is a warning. Works only for a run that
+ autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with
+ execute-sql instead.
feature_flag: autoresearch
autoresearch-models-list:
operation: autoresearch_models_list
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e133c32d79ce..d9071031e92f 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1120,7 +1120,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-materialize-features": {
- "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",
+ "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Also returns what the feature query cost (elapsed_s and rows_read) and hints about features.sql shapes that scale badly. A promoted model must score its inference population under batch limits before it serves, so a slow or heavy query here is a warning. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Materialize training features to the sandbox",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 510c5420b268..4b4fe6fcf84b 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1135,7 +1135,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-materialize-features": {
- "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",
+ "description": "Run your features.sql server-side against the labeled training population and write the train/holdout feature and label parquet files directly into your sandbox. Returns the local paths (train_features_path, train_labels_path, holdout_features_path, holdout_labels_path), row counts, and the feature column list — the feature rows never pass through your context and there is NO 500-row cap. Then pd.read_parquet the returned paths and iterate in Python. Use this to pull training data instead of execute-sql, and re-call it whenever you change features.sql. Also returns what the feature query cost (elapsed_s and rows_read) and hints about features.sql shapes that scale badly. A promoted model must score its inference population under batch limits before it serves, so a slow or heavy query here is a warning. Works only for a run that autoresearch-train-create opened in a PostHog sandbox; an agent training outside PostHog pulls its data with execute-sql instead.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Materialize training features to the sandbox",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 33efe85639f9..a4d7a671f754 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -62747,6 +62747,12 @@ export namespace Schemas {
n_features: number;
/** The numeric feature column names (excludes distinct_id, __label, __fold). */
feature_cols: string[];
+ /** Seconds the server spent on the queries that materialized the matrix. Scoring runs features_sql over the whole inference population on every cadence, so a slow query here is slow there too. */
+ elapsed_s: number;
+ /** Rows ClickHouse read to materialize the matrix. */
+ rows_read: number;
+ /** Advice on the cost of features_sql. A hint does not block the materialization or the upload, but a champion whose features.sql cannot score today's population in time is not promoted. */
+ hints: string[];
}
/**