: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(autoresearch): score the population and emit prediction events (11/22) (#89141)
Andrew Maguirebd9e18dd3901
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.mdindex a9bdf03689fa..2fd96f0e6de8 100644--- a/products/autoresearch/backend/dataset/AGENTS.md+++ b/products/autoresearch/backend/dataset/AGENTS.md@@ -62,6 +62,7 @@ The two branches differ only in cutoff and whether labels and folds are attached- **Any change to what a row means goes here and only here.** If you add a cutoff rule, a population kind, or a label variant next to a caller instead, the trainer and scorer will drift and the failure will be silent.- Keep the training-side `labeled_anchors` CTE and `build_inference_anchors_sql()` symmetrical. They should differ in cutoff, labels, and folds — nothing else.+- Every activity scan here excludes the product's own `autoresearch_prediction` event (`_own_events_excluded_clause()`). A live cadence writes one per scored person, so counting it would keep a person eligible forever on nothing but their own predictions. Add the clause to any new events scan.- New population kinds need the semantic spec in `templates.py`, the compiler branch in `_build_population_kind_conditions()` in `labeling.py` (both row mode and anchor mode), and the required-key rules in the `PopulationDefinitionField` validator in `../presentation/views/serializers.py`. `POPULATION_KINDS` in `labeling.py` is the shared registry; a kind missing its compiler branch is rejected at creation and raises at query time.- Every population kind and every event-property filter is evaluated **per user at T0** during training (the `HAVING` clause of the labeled CTE) and **as of the cutoff** at inference; only person-property filters apply at the scan. Deciding training membership as of `now()` would admit users on activity after T0, including the outcome window, and excluding "ever performed the target" users with a plain row filter would delete exactly the users whose post-T0 adoption provides the positive labels.- Fold 0 is the holdout everywhere. If you change `NUM_FOLDS` or the holdout fold, every recorded `holdout_score` in the database becomes incomparable to new ones.diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.pyindex fd8571d0bcd9..62f25c80a4e2 100644--- a/products/autoresearch/backend/dataset/labeling.py+++ b/products/autoresearch/backend/dataset/labeling.py@@ -94,6 +94,17 @@ def _identified_users_and_clause() -> str:return " AND person.is_identified" if IDENTIFIED_USERS_ONLY else ""+# The product's own output event. Every live cadence writes one per scored person, so an+# activity scan that counted it would keep a person eligible forever on nothing but their+# own predictions, and would count the prediction as the first or last thing they did.+PREDICTION_EVENT_NAME = "autoresearch_prediction"+++def _own_events_excluded_clause(alias: str = "") -> str:+ """`AND event != '<prediction event>'` fragment for an events-table WHERE; pass ``"e."`` for an aliased scan."""+ return f" AND {alias}event != '{PREDICTION_EVENT_NAME}'"++@dataclass(frozen=True, kw_only=True)class _CompiledPopulationFilters:# Row-level fragments for an events scan whose ``person`` resolves through the lazy join.@@ -248,7 +259,7 @@ def _members_within(instant: str, days_param: str, *, predicate: str = "", negatreturn (f"person_id {membership} (SELECT DISTINCT person_id FROM events"f" WHERE timestamp >= {instant} - toIntervalDay({{{days_param}}})"- f" AND timestamp < {instant}{predicate})"+ f" AND timestamp < {instant}{_own_events_excluded_clause()}{predicate})")@@ -501,7 +512,7 @@ def _build_labeled_users_cte(toInt(toUnixTimestamp(now() - toIntervalDay({{horizon}}))) AS cutoff_tsFROM eventsWHERE timestamp >= now() - toIntervalDay({{lookback}})- AND timestamp < now(){training_clause}{identified_clause}+ AND timestamp < now(){_own_events_excluded_clause()}{training_clause}{identified_clause}GROUP BY person_idHAVING first_ts < cutoff_ts{limit_clause}),@@ -525,7 +536,7 @@ def _build_labeled_users_cte(FROM events eINNER JOIN user_t0 u ON e.person_id = u.person_idWHERE e.timestamp >= now() - toIntervalDay({{lookback}})- AND e.timestamp < now()+ AND e.timestamp < now(){_own_events_excluded_clause("e.")}GROUP BY u.person_id, u.t0_ts{anchor_having})"""@@ -620,7 +631,7 @@ def build_eligible_count_sql(countDistinctIf(person_id, {horizon_cond}) AS eligible_allFROM eventsWHERE timestamp >= now() - toIntervalDay({{lookback}})- AND timestamp < now(){training_clause}+ AND timestamp < now(){_own_events_excluded_clause()}{training_clause}"""values: dict[str, Any] = {"horizon": horizon_days,@@ -680,7 +691,7 @@ def build_inference_anchors_sql({cutoff_select} AS cutoff_tsFROM eventsWHERE timestamp >= {cutoff_expr} - toIntervalDay({{lookback}})- AND timestamp < {cutoff_expr}{inf_clause}{identified_clause}+ AND timestamp < {cutoff_expr}{_own_events_excluded_clause()}{inf_clause}{identified_clause}"""values: dict[str, Any] = {"lookback": lookback_days,diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.pyindex 899b46e38a6f..f2cb81ed9dbd 100644--- a/products/autoresearch/backend/dataset/test_labeling.py+++ b/products/autoresearch/backend/dataset/test_labeling.py@@ -21,6 +21,7 @@ from posthog.hogql_queries.query_runner import ExecutionModefrom products.autoresearch.backend.dataset.labeling import (LABELER_QUERY_MODIFIERS,+ PREDICTION_EVENT_NAME,_build_labeled_users_cte,_build_population_conditions,_build_population_kind_conditions,@@ -149,6 +150,14 @@ class TestPopulationFilterCompilation(SimpleTestCase):self.assertEqual(parts, [expected_part])self.assertEqual({k: v for k, v in values.items() if k != "pop_k_0"}, expected_values)+ def test_hostile_key_is_bound_not_interpolated(self) -> None:+ # Keys are bound as HogQL values, so a hostile key must never reach the SQL text.+ hostile_key = "'; DROP TABLE users; --"+ parts, values = _build_population_conditions([{"key": hostile_key, "type": "person", "operator": "is_set"}])+ self.assertEqual(len(parts), 1)+ self.assertNotIn(hostile_key, parts[0])+ self.assertEqual(values["pop_k_0"], hostile_key)+def test_empty_allowlist_matches_nobody(self) -> None:parts, _values = _build_population_conditions([{"key": "plan", "type": "person", "operator": "exact", "value": []}]@@ -230,6 +239,41 @@ class TestPopulationKindCompilation(SimpleTestCase):self.assertIn("person_id IN (SELECT DISTINCT person_id FROM events", sql)self.assertEqual(values["popk_days"], 30)+ @parameterized.expand(+ [+ (+ "inference_anchors",+ lambda: build_inference_anchors_sql(lookback_days=90, inference_population={})[0],+ ),+ (+ "eligible_count",+ lambda: build_eligible_count_sql(horizon_days=7, lookback_days=90, training_population={})[0],+ ),+ (+ "labeler_user_window",+ lambda: build_random_t0_labeler_sql(+ target_event="x", horizon_days=7, lookback_days=90, training_population={}+ )[0],+ ),+ (+ "labeler_labeled_users_aggregate",+ lambda: build_random_t0_labeler_sql(+ target_event="x", horizon_days=7, lookback_days=90, training_population={}+ )[0].split("labeled_users AS")[1],+ ),+ (+ "kind_membership_subquery",+ lambda: build_inference_anchors_sql(+ lookback_days=90, inference_population={"kind": "performed_event_within_days", "days": 30}+ )[0],+ ),+ ]+ )+ def test_activity_scans_exclude_the_prediction_event(self, _name: str, build) -> None:+ # Every live cadence writes one autoresearch_prediction per scored person; a scan that+ # counted it kept a person eligible forever on nothing but their own predictions.+ self.assertIn(f"event != '{PREDICTION_EVENT_NAME}'", build())+def test_inference_backfill_anchors_kind_windows_at_cutoff(self) -> None:sql, _values = build_inference_anchors_sql(lookback_days=90,diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.mdindex 4e1ce27a7dc5..65a672099f4d 100644--- a/products/autoresearch/backend/inference/AGENTS.md+++ b/products/autoresearch/backend/inference/AGENTS.md@@ -5,16 +5,16 @@ Scoring a population with the champion model and writing the result back into PoThis is the cheap, boring, high-frequency half of the product — it runs on the pipeline's cadence (default daily) for every active pipeline, forever.`../training/` is the expensive half that produces what this package consumes.-The cardinal rule: **inference never fits.** Fitting happens once, at training completion. If you find yourself calling a `fit` here on the scoring path, something has gone wrong.+The cardinal rule: **inference never refits a persisted model.** A bundle is fitted once, at training completion, and every cadence loads that `model.pkl`. A recipe-only champion has no persisted model, so it fits its allowlisted sklearn class in process on every cadence; that is the cost of a champion without a bundle, not a refit.-This package landed with `sandbox.py` only. `scoring.py`, `autoresearch_score`, `../presentation/`, `../temporal/`, and `../evaluation/` 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.+This package landed ahead of its callers. `../presentation/`, `../temporal/`, and `../evaluation/` 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.## What lives here- `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.- - `score_via_sandbox()` — **predict run**, called every cadence. Loads the persisted `model.pkl`, materializes _only_ the inference population (cutoff `now()`, no labels, no holdout, no fold), runs `predict.py`, and hands scores to the emitter. A missing `model.pkl` fails the run.+ - `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`, because the anchor SQL reads `person.is_identified` and only resolves under that persons-on-events mode.The train run persists `feature_columns.json` next to `model.pkl`; every predict run sends exactly those columns, in that order, filling an absent or null one with zeros, so the fitted model never sees a column set that depends on today's population. A champion fitted before the file existed falls back to deriving the columns from the scoring rows. A fitted column that holds a present non-numeric value fails the run, because the persisted list bypasses `_numeric_feature_cols()` and zero-filling schema drift would emit a plausible wrong prediction.@@ -24,10 +24,13 @@ This package landed with `sandbox.py` only. `scoring.py`, `autoresearch_score`,Timeouts are asymmetric on purpose — `_TRAIN_TIMEOUT_S` 300s versus `_PREDICT_TIMEOUT_S` 120s — with `_SANDBOX_TTL_S` as the backstop for a worker that dies mid-run. `_MATERIALIZE_ROW_LIMIT` and `_MAX_FEATURE_COLS` together cap what crosses into the sandbox: the row cap alone does not bound the matrix the worker expands, because the agent's SQL chooses the column count.- `scoring.py`- The legacy in-process path plus the event emission that both paths share.- `run_inference_for_pipeline()` is the entry point called by the Temporal activity and by `autoresearch_score`.+ The recipe-only in-process path plus the event emission that both paths share.+ `run_inference_for_pipeline()` is the entry point called by the Temporal activity and by `autoresearch_score`; `score_population()` is the scoring half alone, which the command's dry run calls so it exercises the same route as a real run; the prediction-date guards run inside it, so the dry run refuses exactly the dates the live run refuses.+ A recipe-only champion routes on its recipe: a stub recipe (`stub: true`, SQL evaluated at `now()`) scores by the fixed engagement formula, with the inference population applied inside its query so the row bound measures the population and not the team, and its rows checked against the population count; an agent recipe goes through `validate_runnable_feature_sql()` like a bundle (so a trailing `LIMIT` or an `{anchors}` that sits only in a comment fails the run rather than running without a cutoff) and then fits on the anchored training rows and predicts on the inference anchors. Neither can be backfilled: the fit happens at scoring time on labels decided as of `now()`, so a fit for a past date would learn from outcomes after it. Only a bundle, whose `model.pkl` already exists, is re-scored in the past. The recipe fit validates its training rows the way the sandbox does (one row per person, every row labeled, at most `_MAX_FEATURE_COLS` numeric columns, no duplicate column names), sorts them by person before fitting, because an estimator that samples row indices fits a different model on a different row order despite its seed, seeds a stochastic estimator from the pipeline id unless the recipe sets `random_state`, so a retry refits the same model under the same event UUIDs, and pins `n_jobs=1`, because the fit runs in the worker process. Its probabilities keep full precision, as the bundle path's do.This is the only place that resolves `model_class` through `importlib`, so it is the one genuine code-execution surface — it calls `validate_model_class()` from `../training/recipe_validation.py` before importing. Do not weaken that.- `_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to a `distinct_id` for the emitted event.+ Every query runs as the acting user (the pipeline's creator, or the `--user-id` a command passes), with an explicit bound and a truncation check, including the identity lookup: a bare `SELECT` that HogQL caps at 100 rows would emit most of the population person-less. Every result is refused above `_MAX_FEATURE_COLS` output columns as it is read, before any column is typed, because the numeric filter would otherwise discard the excess only after it was materialized. A run decides its dates once, in `ScoringWindow`: live or backfill, the cutoff every query binds to, and the emit timestamp. The cutoff is the start of the prediction date in UTC for every run, live included, so a retry recomputes the population the failed attempt had (the event UUIDs are the same either way), the feature query and the anchor count agree, and a backfill of a date gets the anchors a live run on that date got. A run that crosses midnight keeps the mode it started in.+ Inference rows are checked against the anchor count on both paths (`count_inference_anchors()`), and training rows against the labeled anchor count (`count_training_anchors()`), because feature SQL that inner joins or filters a joined table in `WHERE` drops people without any row looking wrong.+ `_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to one current `distinct_id` through personhog (`get_persons_by_uuids`), never from event history, because an id read off old events can belong to someone else after a merge or split.## The emitted event@@ -37,14 +40,18 @@ distinct_id: <person distinct_id>properties: $autoresearch_pipeline_id, $autoresearch_p_y, ...```-One event per scored person per run. This is the product's actual output — the person property on the pipeline (`output_person_property`, e.g. `predicted_p_downloaded_file_30d`) is derived from these.+One event per scored person per run, sent as one `capture_batch_internal()` batch. This is the product's actual output — the person property on the pipeline (`output_person_property`, e.g. `predicted_p_downloaded_file_30d`) is derived from these.+Any event the batch does not accept, or accepts with a warning (capture stores the event but has switched something off, such as person processing for a rate-limited distinct id, so the `$set` never lands), fails the run: the event UUIDs are deterministic per (pipeline, model, date, person), so the retry re-sends every row and ingestion keeps one copy, whereas completing with a partial batch would advance the cadence past the people who never received their prediction.+Right before the batch goes out the run re-reads the model's role and fails if promotion has replaced the champion meanwhile, so a superseded model does not write its `$set` over the new champion's. The window between that read and capture is what remains of the race.-Because emission goes through normal ingestion, backdated scoring (`--prediction-date` / `--backfill-days`) is silently dropped when the team has `drop_events_older_than_seconds` set. The events never arrive and nothing errors.+Because emission goes through normal ingestion, a backdated event older than the team's `drop_events_older_than` is accepted by capture and then dropped, so a run refuses a backfill past that threshold instead of recording rows nobody can read. A run also refuses a future prediction date, and a backfill of a population filtered on person properties, because those properties are evaluated as they are today.++The prediction event is itself an event on the person, so every live cadence adds one. The population and anchor scans in `../dataset/labeling.py` exclude it; feature SQL is the agent's, so the fixture's `features.sql` excludes it explicitly and the agent brief says to.## Mental model1. Load the champion for the pipeline.-2. Resolve the inference population and build anchors at cutoff `now()` (`../dataset/labeling.py`).+2. Resolve the inference population and build anchors at the cutoff, the start of the prediction date in UTC (`../dataset/labeling.py`).3. If the champion has an `artifact_prefix`, materialize features into a sandbox and run `predict.py`. Otherwise compile the recorded recipe and score in-process.4. Map `person_id` → `distinct_id` and emit one event each.5. Record an `AutoresearchRun` for the execution.@@ -71,7 +78,7 @@ Before suspecting the model, check that features, labels, and population all key## When editing this flow-- **Never re-fit on the scoring path.** `score_via_sandbox()` loads `model.pkl` and runs `predict.py` only. A fallback that quietly re-fits would make every scoring run expensive and non-deterministic, and concurrent cadences would race to overwrite the pickle. A missing model is a failed run.+- **Never re-fit a persisted model on the scoring path.** `score_via_sandbox()` loads `model.pkl` and runs `predict.py` only. A fallback that quietly re-fits would make every scoring run expensive and non-deterministic, and concurrent cadences would race to overwrite the pickle. A missing model is a failed run. The in-process fit in `scoring.py` is the recipe-only shape's contract, not a fallback, and it must not be reached for a model that has an `artifact_prefix`.- **Keep both champion shapes working** — bundle-backed and recipe-only. Guard on `artifact_prefix` rather than assuming.- `validate_model_class()` must stay on the in-process path. It is not defense in depth there, it is the only defense.- Anything that changes the cutoff, the population, or the anchor SQL belongs in `../dataset/labeling.py`, not here — training and inference share it precisely so they cannot disagree.diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.pyindex 89400a9ac96a..d4adcaf24910 100644--- a/products/autoresearch/backend/inference/sandbox.py+++ b/products/autoresearch/backend/inference/sandbox.py@@ -63,7 +63,9 @@ from posthog.models.user import Userfrom products.autoresearch.backend.dataset.labeling import (LABELER_QUERY_MODIFIERS,+ build_inference_anchors_sql,build_inference_features_sql,+ build_random_t0_labeler_sql,build_training_features_sql,)from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline@@ -111,7 +113,8 @@ _PREDICT_TIMEOUT_S = 120# 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. Mirrors FEATURE_QUERY_LIMIT.+# 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_OUTPUT_JSON = "data/output.json"_SCORES_PARQUET = "data/scores.parquet"@@ -247,10 +250,13 @@ def score_via_sandbox(score_rows = _materialize_score_data(team=team, pipeline=pipeline, feature_sql=bundle.features_sql, cutoff_ts=cutoff_ts, user=acting_user)- feature_cols = _fitted_feature_cols(prefix) or _numeric_feature_cols(score_rows)- # Cheap guards before paying for a sandbox.+ n_train = int((model.metrics or {}).get("n_train") or 0)+ # A population that matches nobody today is a real zero, not a failure: retrying cannot+ # change it, and the recipe path completes the same cadence with no rows.if not score_rows:- raise SandboxInferenceError("No inference rows to score")+ return SandboxScoreResult(scored_rows=[], holdout_auc=model.holdout_score, n_train=n_train, n_features=0)+ feature_cols = _fitted_feature_cols(prefix) or _numeric_feature_cols(score_rows)+ # Cheap guard before paying for a sandbox.if not feature_cols:raise SandboxInferenceError("No numeric feature columns produced by feature SQL")@@ -260,7 +266,7 @@ def score_via_sandbox(return SandboxScoreResult(scored_rows=scored_rows,holdout_auc=model.holdout_score,- n_train=int((model.metrics or {}).get("n_train") or 0),+ n_train=n_train,n_features=len(feature_cols),)@@ -289,20 +295,28 @@ def _resolve_acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: Usdef _validate_bundle_feature_sql(bundle: ArtifactBundle) -> None:"""The recipe snapshot was validated at upload; the bundle's ``features.sql`` is what- actually runs, so it goes through the same validator here. A trailing LIMIT, OFFSET,- or SETTINGS clause is refused as well: inference runs the feature SQL as the top-level- query and appends the framework's own LIMIT after it.+ actually runs, so it goes through the same validator here.+ """+ validate_runnable_feature_sql(bundle.features_sql, source="Bundle features.sql")+++def validate_runnable_feature_sql(feature_sql: str, *, source: str = "feature_sql") -> None:+ """+ ``validate_feature_sql`` plus the rule inference adds: no trailing LIMIT, OFFSET, or+ SETTINGS clause, because inference runs the feature SQL as the top-level query and+ appends the framework's own LIMIT after it. Shared by both champion shapes, so a+ recipe-only champion cannot reach a scoring run with SQL the bundle path would refuse."""try:- validate_feature_sql(bundle.features_sql)+ validate_feature_sql(feature_sql)except RecipeValidationError as exc:- raise SandboxInferenceError(f"Bundle features.sql failed validation: {exc}") from exc- node = parse_select(bundle.features_sql)+ raise SandboxInferenceError(f"{source} failed validation: {exc}") from exc+ node = parse_select(feature_sql)if not isinstance(node, ast.SelectQuery):- raise SandboxInferenceError("Bundle features.sql must be a single SELECT")+ raise SandboxInferenceError(f"{source} must be a single SELECT")if node.limit is not None or node.offset is not None or node.limit_by is not None or node.settings is not None:raise SandboxInferenceError(- "Bundle features.sql must not end with LIMIT, OFFSET, or SETTINGS; the framework bounds the result"+ f"{source} must not end with LIMIT, OFFSET, or SETTINGS; the framework bounds the result")@@ -351,7 +365,8 @@ def materialize_training_data(training_population=pipeline.training_population,)training_rows = _materialize_rows(team=team, sql=train_sql, values=train_values, user=user)- _validate_rows_key_one_person(training_rows, source="training feature_sql")+ expected = count_training_anchors(team=team, pipeline=pipeline, user=user)+ _validate_rows_key_one_person(training_rows, source="training feature_sql", expected_count=expected)# The training wrapper LEFT JOINs the labels onto the feature rows. A feature row# whose distinct_id matched no anchor comes back with NULL label and fold, and the# fold split below would file it as a negative holdout example.@@ -398,16 +413,74 @@ def _materialize_score_data(team=team,)score_rows = _materialize_rows(team=team, sql=score_sql, values=score_values, user=user)- _validate_rows_key_one_person(score_rows, source="inference feature_sql")+ expected = count_inference_anchors(team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user)+ _validate_rows_key_one_person(score_rows, source="inference feature_sql", expected_count=expected)logger.info("autoresearch_score_materialized", pipeline_id=str(pipeline.pk), n_score=len(score_rows), cutoff_ts=cutoff_ts)return score_rows-def _validate_rows_key_one_person(rows: list[dict[str, Any]], *, source: str) -> None:+def count_training_anchors(*, team: Team, pipeline: AutoresearchPipeline, user: User | None = None) -> int:+ """+ How many labeled anchors the trainer materializes, so feature SQL that drops some of them+ fails: a selection-biased fit and a distorted holdout AUC look valid row by row.+ """+ sql, values = build_random_t0_labeler_sql(+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ horizon_days=pipeline.horizon_days,+ lookback_days=pipeline.training_lookback_days,+ training_population=pipeline.training_population,+ sample_limit=None,+ )+ return _count(team=team, sql=sql, values=values, user=user, what="Training anchor count")+++def count_inference_anchors(+ *, team: Team, pipeline: AutoresearchPipeline, cutoff_ts: int | None = None, user: User | None = None+) -> int:+ """+ How many people the inference anchors hold, so a feature query that drops some of them+ fails: an inner join or a WHERE on the joined table loses anchors without any row looking+ wrong, and a lost person is never scored again once the cadence advances past them.+ """+ anchors_sql, values = build_inference_anchors_sql(+ lookback_days=_feature_lookback_days(pipeline),+ inference_population=pipeline.inference_population,+ cutoff_ts=cutoff_ts,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ )+ return _count(+ team=team, sql=f"SELECT count() FROM ({anchors_sql.strip()})", values=values, user=user, what="Anchor count"+ )+++def _count(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> int:+ """Run a query whose first column of its first row is the count the caller wants."""+ try:+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)+ result = run_hogql(+ team=team,+ query=HogQLQuery(query=sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),+ user=user,+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ )+ except Exception as exc:+ raise SandboxInferenceError(f"{what} query failed: {exc}") from exc+ if len(result.rows) != 1 or not result.rows[0]:+ raise SandboxInferenceError(f"{what} query did not return a single row")+ return int(result.rows[0][0])+++def _validate_rows_key_one_person(+ rows: list[dict[str, Any]], *, source: str, expected_count: int | None = None+) -> None:try:- validate_unique_distinct_ids(rows, source=source)+ validate_unique_distinct_ids(rows, source=source, expected_count=expected_count)except RecipeValidationError as exc:raise SandboxInferenceError(str(exc)) from excdiff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pynew file mode 100644index 000000000000..1ce58adf7a51--- /dev/null+++ b/products/autoresearch/backend/inference/scoring.py@@ -0,0 +1,926 @@+"""+Inference: load the champion, score the inference population, and emit one+autoresearch_prediction event per person.++- ``run_inference_for_pipeline()`` is the entry point for the Temporal activity+ (temporal/workflows.py) and for ``autoresearch_score``: it records an+ AutoresearchRun, scores, and emits.+- ``score_population()`` is the scoring half on its own, for a dry run that wants+ the scores without the events.++Event shape:+ event: autoresearch_prediction+ distinct_id: <person distinct_id>+ properties:+ $autoresearch_pipeline_id: str (UUID)+ $autoresearch_model_id: str (UUID)+ $autoresearch_model_role: "champion" | "challenger"+ $autoresearch_target_event: str+ $autoresearch_horizon_days: int+ $autoresearch_p_y: float (the score)+ $autoresearch_prediction_date: str (YYYY-MM-DD)+ $autoresearch_features_hash: str (SHA-256 prefix of the feature row)+ $autoresearch_person_id: str (the person_id every row is keyed on)+"""++import json+import math+import uuid+import hashlib+import inspect+import importlib+from datetime import UTC, date, datetime+from typing import Any++from django.utils import timezone as django_timezone++import numpy as np+import structlog++from posthog.schema import HogQLQuery++from posthog.api.capture import capture_batch_internal+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.person.util import get_persons_by_uuids+from posthog.models.team.team import Team+from posthog.models.user import User++from products.autoresearch.backend.dataset.labeling import (+ LABELER_QUERY_MODIFIERS,+ PREDICTION_EVENT_NAME,+ _build_population_conditions,+ _build_population_kind_conditions,+ _identified_users_and_clause,+ _own_events_excluded_clause,+ _target_condition_for,+ build_inference_features_sql,+ build_training_features_sql,+)+from products.autoresearch.backend.inference.sandbox import (+ _FOLD_COL,+ _HOLDOUT_FOLD,+ _LABEL_COL,+ _MATERIALIZE_ROW_LIMIT,+ _MAX_FEATURE_COLS,+ SandboxInferenceError,+ _num,+ _numeric_feature_cols,+ _resolve_acting_user,+ count_inference_anchors,+ count_training_anchors,+ score_via_sandbox,+ validate_runnable_feature_sql,+)+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun+from products.autoresearch.backend.query import HogQLResult, run_hogql+from products.autoresearch.backend.training.recipe_validation import (+ RecipeValidationError,+ validate_model_class,+ validate_unique_distinct_ids,+)++logger = structlog.get_logger(__name__)++EVENT_SOURCE = "autoresearch_inference"+++class InferenceRunError(Exception):+ """Raised when an inference run must fail (and be retried) rather than complete with wrong output."""+++_RESERVED_COLS = frozenset({"distinct_id", _LABEL_COL, _FOLD_COL})+++# Namespace for deterministic prediction event UUIDs, so a retried scoring activity+# re-emits the same UUID per (pipeline, model, date, person) instead of a duplicate.+_PREDICTION_UUID_NAMESPACE = uuid.UUID("6f9a4a24-0e5c-4a5a-9d0e-2f6a0f0b1c3d")+++def _is_uuid(value: str) -> bool:+ try:+ uuid.UUID(str(value))+ except (ValueError, AttributeError, TypeError):+ return False+ return True+++def _prediction_event_uuid(*, pipeline_id: str, model_id: str, prediction_date: str, person_id: str) -> str:+ return str(uuid.uuid5(_PREDICTION_UUID_NAMESPACE, f"{pipeline_id}:{model_id}:{prediction_date}:{person_id}"))+++@frozen+class ScoredPopulation:+ """One scored row per person; each row keeps its feature columns plus ``p_y``."""++ rows: list[dict[str, Any]]+ # The holdout AUC the serving model advertises: computed on the fly for a recipe-only+ # champion, read from the model row for a bundle.+ holdout_auc: float | None+++@frozen+class ScoringWindow:+ """+ The dates one run scores against, decided once at the entry point. A live run that+ started before midnight and finished after it would otherwise flip to a backfill halfway:+ person-less events at noon, no output property, and no cadence watermark.+ """++ prediction_date: date+ today: date+ now: datetime+ # The instant every query in the run binds to: the start of the prediction date in UTC,+ # for a live run as much as a backfill. A cutoff of now() would give a retry a different+ # population than the attempt it repeats, under the same event UUIDs, so one cadence would+ # hold scores from two populations; anchoring at midnight makes the run reproducible and+ # gives a backfill of the same date the same anchors.+ cutoff_ts: int++ @classmethod+ def for_date(cls, prediction_date: date | None = None) -> "ScoringWindow":+ now = django_timezone.now()+ today = date.today()+ prediction_date = prediction_date or today+ cutoff = datetime(prediction_date.year, prediction_date.month, prediction_date.day, tzinfo=UTC)+ return cls(prediction_date=prediction_date, today=today, now=now, cutoff_ts=int(cutoff.timestamp()))++ @property+ def is_backfill(self) -> bool:+ return self.prediction_date < self.today++ @property+ def is_future(self) -> bool:+ return self.prediction_date > self.today++ @property+ def emit_timestamp(self) -> datetime:+ return _backfill_timestamp(self.prediction_date) if self.is_backfill else self.now+++@frozen+class _EmitResult:+ rows_emitted: int+ score_distribution: dict[str, Any]+++def run_inference_for_pipeline(+ pipeline: AutoresearchPipeline,+ model: AutoresearchModel,+ prediction_date: date | None = None,+ user: User | None = None,+) -> AutoresearchRun:+ """+ Top-level inference entry point. Creates an AutoresearchRun, scores users,+ emits prediction events, and records metrics.++ ``prediction_date`` defaults to today (live scoring). Pass a past date to+ backfill: features are computed as of that date and the events carry that+ date's timestamp, so online validation can score them once the horizon has+ elapsed. A future date fails the run.++ ``user`` is who HogQL applies access control for; it defaults to the+ pipeline's creator.+ """+ window = ScoringWindow.for_date(prediction_date)+ run = AutoresearchRun.objects.create(+ pipeline=pipeline,+ model=model,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ started_at=django_timezone.now(),+ )++ try:+ team = pipeline.team+ acting_user = _acting_user(team=team, pipeline=pipeline, user=user)+ scored = score_population(team=team, pipeline=pipeline, model=model, window=window, user=acting_user)+ emitted = _emit_predictions(+ team=team, pipeline=pipeline, model=model, scored=scored, window=window, user=acting_user+ )++ run.status = AutoresearchRun.Status.COMPLETED+ run.rows_scored = emitted.rows_emitted+ run.metrics = {+ "score_distribution": emitted.score_distribution,+ "stub": bool((model.model_recipe or {}).get("stub", False)),+ "sandbox": bool(model.artifact_prefix),+ "holdout_auc": scored.holdout_auc,+ }+ run.completed_at = django_timezone.now()+ run.save(update_fields=["status", "rows_scored", "metrics", "completed_at"])++ # Only a live run moves the cadence watermark. Backfilling a past date must not+ # make the coordinator think today's scoring already happened.+ if not window.is_backfill:+ pipeline.last_scored_at = run.completed_at+ pipeline.save(update_fields=["last_scored_at", "updated_at"])++ logger.info(+ "autoresearch_inference_complete",+ pipeline_id=str(pipeline.pk),+ model_id=str(model.pk),+ rows_scored=emitted.rows_emitted,+ )+ return run++ except Exception as exc:+ run.status = AutoresearchRun.Status.FAILED+ run.error = str(exc)[:2000]+ run.completed_at = django_timezone.now()+ run.save(update_fields=["status", "error", "completed_at"])+ logger.exception("autoresearch_inference_failed", pipeline_id=str(pipeline.pk))+ raise+++def _acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: User | None) -> User:+ try:+ return _resolve_acting_user(team=team, pipeline=pipeline, user=user)+ except SandboxInferenceError as exc:+ raise InferenceRunError(str(exc)) from exc+++def _check_prediction_date(*, team: Team, pipeline: AutoresearchPipeline, window: ScoringWindow) -> None:+ """+ Refuse the dates that would complete a run with events nobody can use.++ A future date reads as live, so it would compute today's features, stamp a future+ prediction date on them, and advance the cadence. A backfill older than the team's+ ingestion threshold is accepted by capture and then dropped, so the run would record+ every row as scored with no event behind it. A backfill of a population filtered on+ person properties evaluates those properties as they are today, not as they were on+ that date, so the historical membership it claims is fiction.+ """+ prediction_date = window.prediction_date+ if window.is_future:+ raise InferenceRunError(f"Cannot score a future prediction date ({prediction_date.isoformat()})")+ if not window.is_backfill:+ return+ threshold = team.drop_events_older_than+ if threshold is not None and window.now - window.emit_timestamp > threshold:+ raise InferenceRunError(+ f"Cannot backfill {prediction_date.isoformat()}: ingestion drops this team's events older than "+ f"{threshold}, so the predictions would never be stored"+ )+ properties = (pipeline.inference_population or {}).get("properties") or []+ if any(str(prop.get("type", "person")) == "person" for prop in properties if isinstance(prop, dict)):+ raise InferenceRunError(+ "Cannot backfill a population filtered on person properties: membership would be decided on "+ "today's property values, not the values as of the prediction date"+ )+++def _backfill_timestamp(prediction_date: date) -> datetime:+ # Noon UTC so the event lands in that day's window in every project timezone.+ return datetime(prediction_date.year, prediction_date.month, prediction_date.day, 12, tzinfo=UTC)+++def score_population(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ model: AutoresearchModel,+ window: ScoringWindow,+ user: User | None = None,+) -> ScoredPopulation:+ """+ Score the inference population with ``model`` and return the rows without emitting.++ A bundle-backed champion runs its ``predict.py`` in a sandbox against the persisted+ ``model.pkl``. A recipe-only champion has no persisted model: a stub recipe scores by+ a fixed engagement formula, and an agent recipe fits its allowlisted sklearn class on+ the anchored training population and predicts on the inference anchors, in process.+ The agent recipe's SQL goes through the same runnable-SQL validator as a bundle, so a+ recipe with a trailing LIMIT or with ``{anchors}`` only in a comment fails here+ instead of producing a query that runs without a cutoff.++ The prediction-date guards run here rather than in the emitting caller, so the dry run+ refuses exactly the dates the live run refuses.+ """+ _check_prediction_date(team=team, pipeline=pipeline, window=window)+ acting_user = _acting_user(team=team, pipeline=pipeline, user=user)+ cutoff_ts = window.cutoff_ts++ if model.artifact_prefix:+ result = score_via_sandbox(team=team, pipeline=pipeline, model=model, cutoff_ts=cutoff_ts, user=acting_user)+ return ScoredPopulation(rows=result.scored_rows, holdout_auc=result.holdout_auc)++ if window.is_backfill:+ # A recipe-only champion fits at scoring time, and its training labels are decided as of+ # now(), so a fit for a past date would learn from outcomes after that date and hand+ # online validation a lookahead score. Only a persisted model can be re-scored in the past.+ raise InferenceRunError(+ "Only a bundle-backed champion can be backfilled: a recipe-only champion fits at scoring time "+ "on labels decided as of today"+ )+ recipe = model.model_recipe or {}+ if recipe.get("stub"):+ rows = _fetch_stub_feature_rows(team=team, pipeline=pipeline, recipe=recipe, user=acting_user)+ return ScoredPopulation(rows=_score_rows(rows), holdout_auc=model.holdout_score)++ feature_sql = str(recipe.get("feature_sql") or "")+ try:+ validate_runnable_feature_sql(feature_sql, source="Champion recipe feature_sql")+ except SandboxInferenceError as exc:+ raise InferenceRunError(str(exc)) from exc+ return _score_via_anchors(team=team, pipeline=pipeline, recipe=recipe, cutoff_ts=cutoff_ts, user=acting_user)+++def _emit_predictions(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ model: AutoresearchModel,+ scored: ScoredPopulation,+ window: ScoringWindow,+ user: User,+) -> _EmitResult:+ """+ Send one prediction event per scored row in one batch. Any failed event fails the run:+ the event UUIDs are deterministic, so the retry re-sends every row and ingestion keeps+ one copy, whereas completing with a partial batch would advance the cadence past the+ people who never received their prediction or output property.+ """+ if not scored.rows:+ logger.warning("autoresearch_no_scored_rows", pipeline_id=str(pipeline.pk), team_id=team.pk)+ return _EmitResult(rows_emitted=0, score_distribution={})++ is_backfill = window.is_backfill+ prediction_date_str = window.prediction_date.isoformat()+ emit_timestamp = window.emit_timestamp++ _require_still_champion(model)+ # Live runs attach each prediction to the real person: a real distinct_id, a processed+ # person profile, and a $set of the output property. Backfills stay person-less (they+ # exist for online validation, which keys on $autoresearch_person_id) so a past-dated+ # $set cannot clobber a live score.+ distinct_id_by_person = (+ {}+ if is_backfill+ else _resolve_distinct_ids(+ team=team, pipeline=pipeline, person_ids=[str(row["distinct_id"]) for row in scored.rows], user=user+ )+ )+ output_property = pipeline.output_person_property++ events: list[dict[str, Any]] = []+ for row in scored.rows:+ # Every row is keyed on person_id (the feature/score SQL aliases it "distinct_id").+ person_id = str(row["distinct_id"])+ real_distinct_id = distinct_id_by_person.get(person_id)+ attach_to_person = bool(real_distinct_id)+ # Feature values can be datetimes, Decimals, or UUIDs the model ignored; default=str+ # keeps the hash stable for them instead of failing the whole batch.+ features_hash = hashlib.sha256(+ json.dumps({k: v for k, v in row.items() if k != "p_y"}, sort_keys=True, default=str).encode()+ ).hexdigest()[:16]+ props: dict[str, Any] = {+ "$autoresearch_pipeline_id": str(pipeline.pk),+ "$autoresearch_model_id": str(model.pk),+ "$autoresearch_model_role": model.role,+ "$autoresearch_target_event": pipeline.target_event,+ "$autoresearch_horizon_days": pipeline.horizon_days,+ "$autoresearch_p_y": row["p_y"],+ "$autoresearch_prediction_date": prediction_date_str,+ "$autoresearch_features_hash": features_hash,+ "$autoresearch_person_id": person_id,+ }+ if attach_to_person and output_property:+ props["$set"] = {output_property: row["p_y"]}+ events.append(+ {+ "event": PREDICTION_EVENT_NAME,+ "distinct_id": real_distinct_id or person_id,+ "timestamp": emit_timestamp,+ "properties": props,+ "options": {"process_person_profile": attach_to_person},+ "event_uuid": _prediction_event_uuid(+ pipeline_id=str(pipeline.pk),+ model_id=str(model.pk),+ prediction_date=prediction_date_str,+ person_id=person_id,+ ),+ }+ )++ try:+ # The batch-level flag is a safety rail that forces every event person-less when+ # False; a live run needs it on so each event's own option decides.+ result = capture_batch_internal(+ events=events,+ token=team.api_token,+ event_source=EVENT_SOURCE,+ process_person_profile=not is_backfill,+ )+ except Exception as exc:+ logger.exception("autoresearch_prediction_emit_failed", pipeline_id=str(pipeline.pk))+ raise InferenceRunError(f"Prediction events could not be sent: {exc}") from exc+ # A warning is an event capture stored with something switched off, such as person+ # processing for a rate-limited distinct id, so its $set never reaches the person.+ # succeeded() ignores warnings on purpose; this run cannot.+ if not result.succeeded() or result.warnings:+ logger.warning(+ "autoresearch_prediction_emit_partial",+ pipeline_id=str(pipeline.pk),+ dropped=len(result.dropped),+ retried=len(result.retried),+ unaccounted=len(result.unaccounted),+ warnings=len(result.warnings),+ error=result.error,+ )+ sample = [result.results.get(uid) for uid in result.warnings[:3]]+ raise InferenceRunError(+ f"Prediction events were not all accepted ({len(result.dropped)} dropped, "+ f"{len(result.retried)} exhausted retries, {len(result.unaccounted)} unaccounted, "+ f"{len(result.warnings)} stored with a warning{f' e.g. {sample!r}' if sample else ''}"+ f"{', ' + str(result.error.get('error')) if result.error else ''}); failing the run so it is retried"+ )++ return _EmitResult(+ rows_emitted=len(events), score_distribution=_summarize_scores([row["p_y"] for row in scored.rows])+ )+++def _require_still_champion(model: AutoresearchModel) -> None:+ """+ Promotion can swap the champion while a run is scoring with the old one. Re-reading the+ role right before the events go out stops a superseded model from writing its scores+ over the new champion's; the window between this read and capture is the residue.+ """+ if model.role != AutoresearchModel.Role.CHAMPION:+ return+ if not AutoresearchModel.objects.filter(pk=model.pk, role=AutoresearchModel.Role.CHAMPION).exists():+ raise InferenceRunError(+ f"Model {model.pk} stopped being the champion while this run was scoring; the new champion's next "+ "cadence supersedes it"+ )+++# ── Queries ────────────────────────────────────────────────────────────────────────+++def _query(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> HogQLResult:+ """+ Run a person-keyed query as the acting user, fresh, bounded at ``_MATERIALIZE_ROW_LIMIT``.++ HogQL caps a bare SELECT at 100 rows without an error, so every query here carries an+ explicit bound, and a result that fills it is treated as truncated: completing would+ advance the cadence past the people beyond the cap. The persons-on-events modifiers+ are what make ``person.is_identified`` resolve, and the always-calculate mode stops a+ cadence reusing a cached population at a stale cutoff.+ """+ bounded_sql = sql.rstrip().rstrip(";") + f"\nLIMIT {_MATERIALIZE_ROW_LIMIT}"+ try:+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)+ result = run_hogql(+ team=team,+ query=HogQLQuery(query=bounded_sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),+ user=user,+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ )+ except Exception as exc:+ logger.exception("autoresearch_inference_query_failed", team_id=team.pk, what=what)+ raise InferenceRunError(+ f"{what} query failed; failing the run rather than completing it against a partial or unrestricted "+ "population"+ ) from exc+ if result.has_more or len(result.rows) >= _MATERIALIZE_ROW_LIMIT:+ raise InferenceRunError(+ f"{what} query hit the {_MATERIALIZE_ROW_LIMIT}-row limit; the population is likely truncated, "+ "refusing to score a partial population"+ )+ return result+++def _person_rows(result: HogQLResult) -> list[dict[str, Any]]:+ """Rows as dicts with the person key coerced to str, so it is JSON-serializable and joins to str-keyed sets."""+ if not result.rows or not result.columns:+ return []+ # as_dicts() keeps only the last value of a repeated column name, so the matrix would hold+ # fewer features than the SQL declares.+ duplicates = sorted({c for c in result.columns if result.columns.count(c) > 1})+ if duplicates:+ raise InferenceRunError(f"Feature SQL returned duplicate output columns: {', '.join(duplicates)}")+ # Counted before any column is typed: the numeric filter discards non-numeric columns, so+ # a result padded with string aliases would pass the matrix cap after being materialized.+ output_cols = [c for c in result.columns if c not in _RESERVED_COLS]+ if len(output_cols) > _MAX_FEATURE_COLS:+ raise InferenceRunError(+ f"Feature SQL returned {len(output_cols)} output columns; at most {_MAX_FEATURE_COLS} are allowed"+ )+ rows = result.as_dicts()+ for row in rows:+ if row.get("distinct_id") is not None:+ row["distinct_id"] = str(row["distinct_id"])+ return rows+++def _require_one_row_per_person(rows: list[dict[str, Any]], *, source: str, expected_count: int | None) -> None:+ try:+ validate_unique_distinct_ids(rows, source=source, expected_count=expected_count)+ except RecipeValidationError as exc:+ raise InferenceRunError(str(exc)) from exc+++def _feature_lookback_days(pipeline: AutoresearchPipeline) -> int:+ # Same window as sandbox._feature_lookback_days: 4x horizon, at least 30 days.+ return max(30, pipeline.horizon_days * 4)+++def _fetch_stub_feature_rows(+ *, team: Team, pipeline: AutoresearchPipeline, recipe: dict[str, Any], user: User+) -> list[dict[str, Any]]:+ """+ Run a stub recipe's feature SQL restricted to the inference population.++ The stub's SQL is templated in ``training/stub.py``, evaluates at now(), and carries+ no ``{anchors}``, so it does not go through the anchors builders. The population is+ applied inside the query rather than on the returned rows, so the row bound measures+ the population being scored and not every person on the team. The rows are checked+ against the population count, as the anchored paths check theirs against the anchors,+ because stub SQL that drops a member leaves every returned row looking valid.+ """+ feature_sql = str(recipe.get("feature_sql") or "")+ if not feature_sql:+ logger.warning("autoresearch_empty_feature_sql", pipeline_id=str(pipeline.pk))+ return []+ lookback_days = _feature_lookback_days(pipeline)+ feature_sql = feature_sql.replace("{lookback_days}", str(lookback_days)).rstrip().rstrip(";")+ population = _population_query(+ population=pipeline.inference_population,+ lookback_days=lookback_days,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ )+ sql, values = feature_sql, {}+ if population is not None:+ sql = f"SELECT * FROM ({feature_sql}) AS f WHERE f.distinct_id IN ({population.sql})"+ values = population.values+ rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Feature"))+ expected = _count_population(team=team, population=population, user=user) if population is not None else None+ _require_one_row_per_person(rows, source="stub feature_sql", expected_count=expected)+ return rows+++@frozen+class _PopulationQuery:+ sql: str+ values: dict[str, Any]+++def _population_query(+ *,+ population: dict[str, Any] | None,+ lookback_days: int,+ target_event: str = "",+ target_definition: dict[str, Any] | None = None,+ team: Team | None = None,+) -> _PopulationQuery | None:+ """+ A ``SELECT DISTINCT person_id`` for the people in the inference population, restricted+ to identified users under the v1 scope. None only when nothing restricts the population.+ A configured filter that cannot be compiled raises, because widening to everyone is+ the failure being prevented.+ """+ properties = (population or {}).get("properties", [])+ parts, values = _build_population_conditions(properties)+ target_cond, target_values = _target_condition_for(+ population, target_event=target_event, target_definition=target_definition, team=team+ )+ compiled_kind = _build_population_kind_conditions(population, target_cond=target_cond)+ parts.extend(compiled_kind.where_parts)+ values.update(target_values)+ values.update(compiled_kind.values)+ identified_clause = _identified_users_and_clause()++ if not parts and not identified_clause:+ return None++ values["lookback"] = lookback_days+ # The upper bound keeps a future-dated or imported event from making someone eligible today.+ where_clause = (+ f"timestamp >= now() - toIntervalDay({{lookback}}) AND timestamp < now(){_own_events_excluded_clause()}"+ )+ if parts:+ where_clause += " AND " + " AND ".join(parts)+ where_clause += identified_clause+ return _PopulationQuery(sql=f"SELECT DISTINCT person_id FROM events WHERE {where_clause}", values=values)+++def _count_population(*, team: Team, population: _PopulationQuery, user: User) -> int:+ result = _query(+ team=team,+ sql=f"SELECT count() FROM ({population.sql})",+ values=population.values,+ user=user,+ what="Population count",+ )+ if len(result.rows) != 1 or not result.rows[0]:+ raise InferenceRunError("Population count query did not return a single row")+ return int(result.rows[0][0])+++def _resolve_distinct_ids(+ *, team: Team, pipeline: AutoresearchPipeline, person_ids: list[str], user: User+) -> dict[str, str]:+ """+ Map each person_id to one of that person's current distinct_ids.++ Every row is keyed on person_id, but a live event attaches to a person through a+ distinct_id, so the event goes out under one of the person's real ids rather than the+ person UUID. The mapping comes from personhog, the identity source of truth: an id read+ off event history can belong to someone else after a merge or split. A person with no+ resolvable id is emitted person-less by the caller.+ """+ resolvable = [p for p in person_ids if _is_uuid(p)]+ if len(resolvable) != len(person_ids):+ logger.warning(+ "autoresearch_unresolvable_person_ids",+ pipeline_id=str(pipeline.pk),+ skipped=len(person_ids) - len(resolvable),+ )+ if not resolvable:+ return {}+ try:+ persons = get_persons_by_uuids(team.pk, resolvable, distinct_id_limit=1)+ except Exception as exc:+ logger.exception("autoresearch_identity_resolution_failed", pipeline_id=str(pipeline.pk))+ raise InferenceRunError(+ "Identity resolution failed; failing the run rather than emitting every prediction person-less"+ ) from exc+ return {str(person.uuid): person.distinct_ids[0] for person in persons if person.distinct_ids}+++# ── Recipe-only champions ─────────────────────────────────────────────────────────+++def _score_via_anchors(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ recipe: dict[str, Any],+ cutoff_ts: int | None,+ user: User,+) -> ScoredPopulation:+ """+ Score with an agent recipe that has no bundle.++ The recipe's feature SQL runs twice: against the labeled training anchors (per-user+ random T0, label, fold) and against the inference anchors (cutoff now(), or the+ backfill instant). The model fits on the training folds, reports a holdout AUC on+ fold 0, and predicts on the inference rows. Without training rows the stub formula+ scores the inference rows, so a half-broken recipe still emits zero-information+ predictions instead of nothing.+ """+ feature_sql = str(recipe.get("feature_sql") or "").replace("{lookback_days}", str(_feature_lookback_days(pipeline)))+ training_rows = _fetch_training_rows(team=team, pipeline=pipeline, feature_sql=feature_sql, user=user)+ inference_rows = _fetch_inference_rows(+ team=team, pipeline=pipeline, feature_sql=feature_sql, cutoff_ts=cutoff_ts, user=user+ )+ if not inference_rows:+ logger.warning("autoresearch_no_inference_rows", pipeline_id=str(pipeline.pk))+ return ScoredPopulation(rows=[], holdout_auc=None)+ if not training_rows:+ logger.warning("autoresearch_no_training_rows_anchored_fallback_stub", pipeline_id=str(pipeline.pk))+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)+ return _fit_on_training_predict_on_inference(+ training_rows=training_rows, inference_rows=inference_rows, recipe=recipe, pipeline_id=str(pipeline.pk)+ )+++def _fetch_training_rows(+ *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User+) -> list[dict[str, Any]]:+ """The recipe's feature SQL against the labeled anchors: one row per person with ``__label`` and ``__fold``."""+ sql, values = build_training_features_sql(+ feature_sql=feature_sql,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ horizon_days=pipeline.horizon_days,+ lookback_days=pipeline.training_lookback_days,+ training_population=pipeline.training_population,+ )+ rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Training features"))+ try:+ expected = count_training_anchors(team=team, pipeline=pipeline, user=user)+ except SandboxInferenceError as exc:+ raise InferenceRunError(str(exc)) from exc+ _require_one_row_per_person(rows, source="training feature_sql", expected_count=expected)+ # The wrapper LEFT JOINs the labels onto the feature rows; a row that matched no anchor+ # would be filed as a negative holdout example.+ unlabeled = sum(1 for r in rows if r.get(_LABEL_COL) is None or r.get(_FOLD_COL) is None)+ if unlabeled:+ raise InferenceRunError(+ f"{unlabeled} training feature row(s) matched no labeled anchor; distinct_id must be the anchor person_id"+ )+ return rows+++def _fetch_inference_rows(+ *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, cutoff_ts: int | None, user: User+) -> list[dict[str, Any]]:+ """+ The recipe's feature SQL against the inference anchors: one row per eligible person.++ The row count is checked against the anchor count, because feature SQL that inner+ joins or filters a joined table drops people without any row looking wrong. The training+ rows get the same check against the labeled anchors.+ """+ sql, values = build_inference_features_sql(+ feature_sql=feature_sql,+ lookback_days=_feature_lookback_days(pipeline),+ inference_population=pipeline.inference_population,+ cutoff_ts=cutoff_ts,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ )+ rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Inference features"))+ try:+ expected = count_inference_anchors(team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user)+ except SandboxInferenceError as exc:+ raise InferenceRunError(str(exc)) from exc+ _require_one_row_per_person(rows, source="inference feature_sql", expected_count=expected)+ return rows+++def _fit_on_training_predict_on_inference(+ *,+ training_rows: list[dict[str, Any]],+ inference_rows: list[dict[str, Any]],+ recipe: dict[str, Any],+ pipeline_id: str,+) -> ScoredPopulation:+ """+ Fit the recipe's allowlisted sklearn class on the training folds, score the holdout+ fold for the AUC the run records, and predict on the inference rows. A fit or predict+ failure falls back to the stub formula so the cadence still emits.+ """+ # Feature SQL without an ORDER BY returns rows in any order, and an estimator that+ # samples row indices fits a different model on a different order despite its seed.+ training_rows = sorted(training_rows, key=lambda r: str(r.get("distinct_id")))+ feature_cols = _numeric_feature_cols(training_rows)+ if not feature_cols:+ logger.warning("autoresearch_no_numeric_features", pipeline_id=pipeline_id)+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)+ if len(feature_cols) > _MAX_FEATURE_COLS:+ # The row bound does not bound the matrix: the agent's SQL chooses the column count.+ raise InferenceRunError(+ f"Recipe feature SQL returned {len(feature_cols)} numeric columns; at most {_MAX_FEATURE_COLS} are allowed"+ )++ train_rows = [r for r in training_rows if (r.get(_FOLD_COL) or 0) != _HOLDOUT_FOLD]+ holdout_rows = [r for r in training_rows if (r.get(_FOLD_COL) or 0) == _HOLDOUT_FOLD]+ if not train_rows:+ logger.warning("autoresearch_no_train_fold_rows", pipeline_id=pipeline_id)+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)++ X_train = _matrix(train_rows, feature_cols)+ y_train = _labels(train_rows)+ n_pos = int(y_train.sum())+ n_neg = int(len(y_train) - n_pos)+ if n_pos < 5 or n_neg < 5:+ logger.warning("autoresearch_insufficient_labels", pipeline_id=pipeline_id, n_pos=n_pos, n_neg=n_neg)+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)++ model_class_path = str(recipe.get("model_class", "sklearn.linear_model.LogisticRegression"))+ try:+ estimator = _estimator_for(recipe, seed=_stable_seed(pipeline_id))+ estimator.fit(X_train, y_train)+ except Exception:+ logger.exception("autoresearch_anchored_fit_failed", pipeline_id=pipeline_id, model_class=model_class_path)+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)++ holdout_auc = _holdout_auc(estimator, holdout_rows, feature_cols, pipeline_id=pipeline_id)++ # A present non-numeric value in a fitted column fails the run: zero-filling it would+ # emit a plausible wrong prediction, the same rule the sandbox path applies.+ X_score = _matrix(inference_rows, feature_cols)+ try:+ proba = estimator.predict_proba(X_score)[:, 1]+ except Exception:+ logger.exception("autoresearch_anchored_predict_failed", pipeline_id=pipeline_id, model_class=model_class_path)+ return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=holdout_auc)++ logger.info(+ "autoresearch_anchored_fit_complete",+ pipeline_id=pipeline_id,+ model_class=model_class_path,+ n_train=len(y_train),+ n_pos=n_pos,+ n_features=len(feature_cols),+ holdout_auc=holdout_auc,+ )+ # Full precision, as _join_scores keeps for a bundle: rounding would tie predictions that+ # online validation ranks against each other.+ scored = [{**row, "p_y": float(p)} for row, p in zip(inference_rows, proba)]+ return ScoredPopulation(rows=scored, holdout_auc=holdout_auc)+++def _stable_seed(pipeline_id: str) -> int:+ return int(hashlib.sha256(pipeline_id.encode()).hexdigest()[:8], 16)+++def _estimator_for(recipe: dict[str, Any], *, seed: int) -> Any:+ """+ Instantiate the recipe's allowlisted sklearn class. This is the one in-process importlib+ surface, and the allowlist is the only defense, because a recipe-only champion has no+ sandbox around its model class.++ A stochastic estimator gets a seed derived from the pipeline unless the recipe sets one:+ a retry after a partial capture refits, and two fits that disagree would leave one+ cadence with scores from both, because the event UUIDs are the same either way.+ """+ model_class_path = str(recipe.get("model_class", "sklearn.linear_model.LogisticRegression"))+ validate_model_class(model_class_path)+ module_path, class_name = model_class_path.rsplit(".", 1)+ model_class = getattr(importlib.import_module(module_path), class_name)+ params = dict(recipe.get("model_params") or {})+ accepted = inspect.signature(model_class.__init__).parameters+ if "random_state" in accepted:+ params.setdefault("random_state", seed)+ if "n_jobs" in accepted:+ # The fit runs in the worker process; an agent's n_jobs=-1 would take every core it has.+ params["n_jobs"] = 1+ return model_class(**params)+++def _matrix(rows: list[dict[str, Any]], feature_cols: list[str]) -> np.ndarray:+ try:+ return np.array([[_num(r.get(c), col=c) for c in feature_cols] for r in rows], dtype=np.float64)+ except SandboxInferenceError as exc:+ raise InferenceRunError(str(exc)) from exc+++def _labels(rows: list[dict[str, Any]]) -> np.ndarray:+ return np.array([int(r.get(_LABEL_COL) or 0) for r in rows], dtype=np.int32)+++def _holdout_auc(+ estimator: Any, holdout_rows: list[dict[str, Any]], feature_cols: list[str], *, pipeline_id: str+) -> float | None:+ """AUC on fold 0, or None when the holdout is empty, single-class, or fails to score."""+ if not holdout_rows:+ return None+ try:+ # Deferred to keep the heavy dependency off the import path.+ from sklearn.metrics import roc_auc_score # noqa: PLC0415++ y_holdout = _labels(holdout_rows)+ if len(set(y_holdout.tolist())) < 2:+ return None+ p_holdout = estimator.predict_proba(_matrix(holdout_rows, feature_cols))[:, 1]+ return round(float(roc_auc_score(y_holdout, p_holdout)), 4)+ except Exception:+ logger.exception("autoresearch_holdout_auc_failed", pipeline_id=pipeline_id)+ return None+++def _score_rows(feature_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """+ The stub formula: a sigmoid of event volume against recency, as a proxy for engagement.+ Serves stub champions, and any recipe-only champion whose fit could not run.+ """+ if not feature_rows:+ return []++ # The stub SQL names the column by its window ("events_total_30d"); the fixture SQL+ # names it "events_total".+ total_col = next(+ (col for col in feature_rows[0].keys() if col.startswith("events_total_") or col == "events_total"),+ None,+ )+ days_col = next((col for col in feature_rows[0].keys() if "days_since_last" in col), None)++ def _sigmoid(x: float) -> float:+ return 1.0 / (1.0 + math.exp(-x))++ def _stub_score(row: dict[str, Any]) -> float:+ activity = float(row.get(total_col) or 0) if total_col else 0.0+ # Zero days since the last event is the most recent a person can be; only an+ # absent value falls back to a month.+ recency_value = row.get(days_col) if days_col else None+ recency = float(recency_value) if recency_value is not None else 30.0+ raw = (activity / 20.0) - (recency / 14.0)+ return round(_sigmoid(raw), 4)++ return [{**row, "p_y": _stub_score(row)} for row in feature_rows if row.get("distinct_id")]+++def _summarize_scores(scores: list[float]) -> dict[str, Any]:+ if not scores:+ return {}+ n = len(scores)+ sorted_scores = sorted(scores)+ return {+ "count": n,+ "mean": round(sum(scores) / n, 4),+ "p10": round(sorted_scores[int(n * 0.10)], 4),+ "p50": round(sorted_scores[int(n * 0.50)], 4),+ "p90": round(sorted_scores[int(n * 0.90)], 4),+ "min": round(sorted_scores[0], 4),+ "max": round(sorted_scores[-1], 4),+ }diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.pynew file mode 100644index 000000000000..d6175d2596ab--- /dev/null+++ b/products/autoresearch/backend/inference/test_inference.py@@ -0,0 +1,807 @@+from datetime import UTC, date, datetime, timedelta+from uuid import uuid4++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.api.capture import CaptureInternalResult++from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME+from products.autoresearch.backend.inference import scoring+from products.autoresearch.backend.inference.sandbox import _MATERIALIZE_ROW_LIMIT, SandboxScoreResult+from products.autoresearch.backend.inference.scoring import (+ InferenceRunError,+ ScoredPopulation,+ ScoringWindow,+ _estimator_for,+ _fetch_inference_rows,+ _fetch_stub_feature_rows,+ _fetch_training_rows,+ _fit_on_training_predict_on_inference,+ _resolve_distinct_ids,+ _score_rows,+ run_inference_for_pipeline,+ score_population,+)+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun+from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.testing import TeamScopedTestMixin++_STUB_RECIPE = {+ "feature_sql": "SELECT person_id AS distinct_id, count() AS events_total_30d FROM events GROUP BY person_id",+ "model_class": "sklearn.linear_model.LogisticRegression",+ "model_params": {},+ "stub": True,+}+_ANCHORS_FEATURE_SQL = (+ "SELECT a.person_id AS distinct_id, count() AS events_total FROM {anchors} a GROUP BY a.person_id"+)+_ANCHORS_RECIPE = {+ "feature_sql": _ANCHORS_FEATURE_SQL,+ "model_class": "sklearn.linear_model.LogisticRegression",+ "model_params": {},+}+_STUB_ROWS = [+ {"distinct_id": "user-1", "events_total_30d": 50, "days_since_last_seen": 2},+ {"distinct_id": "user-2", "events_total_30d": 10, "days_since_last_seen": 15},+]+++def _accepted(events: list[dict]) -> CaptureInternalResult:+ return CaptureInternalResult(status_code=200, ok=[e["event_uuid"] for e in events])+++def _capture_accepting_everything() -> MagicMock:+ return MagicMock(side_effect=lambda **kwargs: _accepted(kwargs["events"]))+++class TestScoreRows(SimpleTestCase):+ def test_score_rows_produces_values_between_0_and_1(self):+ rows = [+ {"distinct_id": "user-1", "events_total_30d": 100, "days_since_last_seen": 0},+ {"distinct_id": "user-2", "events_total_30d": 0, "days_since_last_seen": 30},+ {"distinct_id": "user-3", "events_total_30d": 50, "days_since_last_seen": 5},+ ]+ scored = _score_rows(rows)+ assert len(scored) == 3+ for row in scored:+ assert 0.0 <= row["p_y"] <= 1.0, f"Score {row['p_y']} for {row['distinct_id']} out of range"++ def test_score_rows_higher_activity_scores_higher(self):+ rows = [+ {"distinct_id": "active", "events_total_30d": 200, "days_since_last_seen": 0},+ {"distinct_id": "inactive", "events_total_30d": 0, "days_since_last_seen": 30},+ ]+ scored = {r["distinct_id"]: r["p_y"] for r in _score_rows(rows)}+ assert scored["active"] > scored["inactive"]++ def test_score_rows_treats_zero_days_since_last_seen_as_most_recent(self):+ rows = [+ {"distinct_id": "today", "events_total_30d": 10, "days_since_last_seen": 0},+ {"distinct_id": "stale", "events_total_30d": 10, "days_since_last_seen": 30},+ {"distinct_id": "unknown", "events_total_30d": 10, "days_since_last_seen": None},+ ]+ scored = {r["distinct_id"]: r["p_y"] for r in _score_rows(rows)}+ assert scored["today"] > scored["stale"]+ assert scored["unknown"] == scored["stale"]++ def test_score_rows_empty_input(self):+ assert _score_rows([]) == []+++class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):+ def _make_pipeline_and_model(self, **pipeline_kwargs) -> tuple[AutoresearchPipeline, AutoresearchModel]:+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="Test",+ target_event="$pageview",+ horizon_days=7,+ output_person_property="predicted_p_pageview",+ **pipeline_kwargs,+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ model_recipe=_STUB_RECIPE,+ recipe_hash="deadbeef",+ holdout_score=0.7,+ )+ return pipeline, model++ def _run_live(self, pipeline, model, capture: MagicMock, rows=_STUB_ROWS, resolved=None) -> AutoresearchRun:+ with (+ patch.object(scoring, "_fetch_stub_feature_rows", return_value=rows),+ patch.object(scoring, "_resolve_distinct_ids", return_value=resolved or {}),+ patch.object(scoring, "capture_batch_internal", capture),+ ):+ return run_inference_for_pipeline(pipeline=pipeline, model=model)++ def test_run_inference_emits_one_batch_and_records_the_run(self):+ pipeline, model = self._make_pipeline_and_model()+ capture = _capture_accepting_everything()++ run = self._run_live(pipeline, model, capture, resolved={"user-1": "real-distinct-id"})++ assert run.status == AutoresearchRun.Status.COMPLETED+ assert run.rows_scored == 2+ assert run.metrics["holdout_auc"] == 0.7+ assert capture.call_count == 1+ kwargs = capture.call_args.kwargs+ events = kwargs["events"]+ assert kwargs["process_person_profile"] is True+ assert [e["event"] for e in events] == [PREDICTION_EVENT_NAME, PREDICTION_EVENT_NAME]+ by_person = {e["properties"]["$autoresearch_person_id"]: e for e in events}+ # A resolved person is attached to their real distinct_id and gets the output property;+ # an unresolved one stays person-less so a UUID never becomes a person.+ assert by_person["user-1"]["distinct_id"] == "real-distinct-id"+ assert by_person["user-1"]["options"] == {"process_person_profile": True}+ assert by_person["user-1"]["properties"]["$set"] == {+ "predicted_p_pageview": by_person["user-1"]["properties"]["$autoresearch_p_y"]+ }+ assert by_person["user-2"]["distinct_id"] == "user-2"+ assert by_person["user-2"]["options"] == {"process_person_profile": False}+ assert "$set" not in by_person["user-2"]["properties"]+ pipeline.refresh_from_db()+ assert pipeline.last_scored_at is not None++ def test_run_inference_zero_rows_completes_without_emitting(self):+ pipeline, model = self._make_pipeline_and_model()+ capture = _capture_accepting_everything()+ run = self._run_live(pipeline, model, capture, rows=[])+ assert run.status == AutoresearchRun.Status.COMPLETED+ assert run.rows_scored == 0+ capture.assert_not_called()++ @parameterized.expand(+ [+ ("transport_failure", Exception("capture unavailable"), None),+ (+ "one_event_dropped",+ None,+ lambda events: CaptureInternalResult(+ status_code=200, ok=[events[0]["event_uuid"]], dropped=[events[1]["event_uuid"]]+ ),+ ),+ (+ "one_event_stored_with_a_warning",+ None,+ lambda events: CaptureInternalResult(+ status_code=200,+ ok=[events[0]["event_uuid"]],+ warnings=[events[1]["event_uuid"]],+ results={events[1]["event_uuid"]: {"result": "warning", "message": "person processing disabled"}},+ ),+ ),+ ]+ )+ def test_any_emit_failure_fails_the_run(self, _name, side_effect, result_for):+ # Completing with a partial batch advanced last_scored_at past the people who never+ # received their prediction; the deterministic UUIDs make a full replay safe instead.+ pipeline, model = self._make_pipeline_and_model()+ capture = MagicMock(side_effect=side_effect or (lambda **kwargs: result_for(kwargs["events"])))++ with self.assertRaises(InferenceRunError):+ self._run_live(pipeline, model, capture)++ run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")+ assert run.status == AutoresearchRun.Status.FAILED+ pipeline.refresh_from_db()+ assert pipeline.last_scored_at is None++ def test_champion_replaced_during_scoring_fails_before_emitting(self):+ # A superseded model's $set would overwrite the new champion's live property.+ pipeline, model = self._make_pipeline_and_model()+ capture = _capture_accepting_everything()++ def archive_then_return_rows(**_kwargs):+ AutoresearchModel.objects.filter(pk=model.pk).update(role=AutoresearchModel.Role.ARCHIVED)+ return _STUB_ROWS++ with (+ patch.object(scoring, "_fetch_stub_feature_rows", side_effect=archive_then_return_rows),+ patch.object(scoring, "_resolve_distinct_ids", return_value={}),+ patch.object(scoring, "capture_batch_internal", capture),+ ):+ with self.assertRaises(InferenceRunError):+ run_inference_for_pipeline(pipeline=pipeline, model=model)+ capture.assert_not_called()++ def test_prediction_events_are_identical_across_a_retry(self):+ pipeline, model = self._make_pipeline_and_model()+ first = _capture_accepting_everything()+ second = _capture_accepting_everything()+ self._run_live(pipeline, model, first)+ self._run_live(pipeline, model, second)+ assert [e["event_uuid"] for e in first.call_args.kwargs["events"]] == [+ e["event_uuid"] for e in second.call_args.kwargs["events"]+ ]++ def test_pipeline_without_a_creator_fails_instead_of_querying_with_no_user(self):+ # With no acting user HogQL fails closed and silently masks the pipeline from its own data.+ pipeline, model = self._make_pipeline_and_model()+ pipeline.created_by = None+ pipeline.save(update_fields=["created_by"])+ with patch.object(scoring, "run_hogql") as hogql:+ with self.assertRaises(InferenceRunError):+ run_inference_for_pipeline(pipeline=pipeline, model=model)+ hogql.assert_not_called()+++@time_machine.travel("2026-09-11T12:00:00Z", tick=False)+class TestPredictionDateGuards(TeamScopedTestMixin, BaseTest):+ def _pipeline_and_model(self, **pipeline_kwargs) -> tuple[AutoresearchPipeline, AutoresearchModel]:+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="Dates",+ target_event="$pageview",+ horizon_days=7,+ **pipeline_kwargs,+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe=_ANCHORS_RECIPE, recipe_hash="abc"+ )+ return pipeline, model++ def _assert_refused(self, pipeline, model, prediction_date, score: MagicMock):+ with patch.object(scoring, "_score_via_anchors", score):+ with self.assertRaises(InferenceRunError):+ run_inference_for_pipeline(pipeline=pipeline, model=model, prediction_date=prediction_date)+ score.assert_not_called()+ run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")+ assert run.status == AutoresearchRun.Status.FAILED++ def test_future_prediction_date_is_refused(self):+ # A future date reads as live: today's features under a future label.+ pipeline, model = self._pipeline_and_model()+ self._assert_refused(pipeline, model, date.today() + timedelta(days=1), MagicMock())++ def test_backfill_past_the_teams_drop_threshold_is_refused(self):+ # Capture accepts the events and ingestion drops them, so the run would record rows+ # scored with nothing behind them.+ self.team.drop_events_older_than = timedelta(days=7)+ self.team.save(update_fields=["drop_events_older_than"])+ pipeline, model = self._pipeline_and_model()+ self._assert_refused(pipeline, model, date.today() - timedelta(days=30), MagicMock())++ def test_backfill_of_a_person_property_population_is_refused(self):+ # Person properties are evaluated as they are today, so the historical membership+ # the backfill claims would be fiction.+ pipeline, model = self._pipeline_and_model(+ inference_population={+ "properties": [{"key": "plan", "type": "person", "operator": "exact", "value": "pro"}]+ }+ )+ self._assert_refused(pipeline, model, date.today() - timedelta(days=3), MagicMock())++ def test_the_dry_run_route_applies_the_same_date_guards(self):+ pipeline, model = self._pipeline_and_model(+ inference_population={+ "properties": [{"key": "plan", "type": "person", "operator": "exact", "value": "pro"}]+ }+ )+ model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"+ model.save(update_fields=["artifact_prefix"])+ with patch.object(scoring, "score_via_sandbox") as sandbox:+ with self.assertRaises(InferenceRunError):+ score_population(+ team=self.team,+ pipeline=pipeline,+ model=model,+ window=ScoringWindow.for_date(date.today() - timedelta(days=3)),+ user=self.user,+ )+ sandbox.assert_not_called()++ def test_backfilling_a_past_date_leaves_last_scored_at_alone(self):+ # Advancing the watermark on a backfill makes the coordinator treat the pipeline as+ # freshly scored, suppressing today's live run for a whole cadence.+ pipeline, model = self._pipeline_and_model()+ model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"+ model.save(update_fields=["artifact_prefix"])+ sandbox_result = SandboxScoreResult(+ scored_rows=[{"distinct_id": str(uuid4()), "p_y": 0.4}], holdout_auc=0.6, n_train=1, n_features=1+ )+ with (+ patch.object(scoring, "score_via_sandbox", return_value=sandbox_result) as sandbox,+ patch.object(scoring, "capture_batch_internal", _capture_accepting_everything()) as capture,+ ):+ run = run_inference_for_pipeline(+ pipeline=pipeline, model=model, prediction_date=date.today() - timedelta(days=30)+ )++ assert run.status == AutoresearchRun.Status.COMPLETED+ assert capture.call_args.kwargs["process_person_profile"] is False+ assert isinstance(sandbox.call_args.kwargs["cutoff_ts"], int)+ pipeline.refresh_from_db()+ assert pipeline.last_scored_at is None++ @parameterized.expand([("stub", _STUB_RECIPE), ("anchors", _ANCHORS_RECIPE)])+ def test_backfilling_a_recipe_only_champion_is_refused(self, _name, recipe):+ pipeline, model = self._pipeline_and_model()+ model.model_recipe = recipe+ model.save(update_fields=["model_recipe"])+ with (+ patch.object(scoring, "_fetch_stub_feature_rows") as stub,+ patch.object(scoring, "_score_via_anchors") as anchors,+ ):+ with self.assertRaises(InferenceRunError):+ run_inference_for_pipeline(+ pipeline=pipeline, model=model, prediction_date=date.today() - timedelta(days=30)+ )+ stub.assert_not_called()+ anchors.assert_not_called()+++@time_machine.travel("2026-09-11T12:00:00Z", tick=False)+class TestRecipeRouting(TeamScopedTestMixin, BaseTest):+ def _pipeline_and_model(self, recipe: dict) -> tuple[AutoresearchPipeline, AutoresearchModel]:+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Routing", target_event="$pageview", horizon_days=7+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe=recipe, recipe_hash="abc"+ )+ return pipeline, model++ @parameterized.expand(+ [+ ("trailing_limit", _ANCHORS_FEATURE_SQL + " LIMIT 10"),+ (+ "anchors_only_in_a_comment",+ "-- reads {anchors}\nSELECT person_id AS distinct_id, count() AS events_total FROM events GROUP BY person_id",+ ),+ ("no_anchors_at_all", "SELECT person_id AS distinct_id, count() AS n FROM events GROUP BY person_id"),+ ]+ )+ def test_recipe_sql_the_bundle_path_would_refuse_fails_the_run(self, _name, feature_sql):+ # A trailing LIMIT makes the appended framework bound a parse error; a placeholder that+ # survives only in a comment runs the query with no anchor and no cutoff.+ pipeline, model = self._pipeline_and_model({**_ANCHORS_RECIPE, "feature_sql": feature_sql})+ with patch.object(scoring, "_score_via_anchors") as anchored, patch.object(scoring, "run_hogql") as hogql:+ with self.assertRaises(InferenceRunError):+ score_population(+ team=self.team, pipeline=pipeline, model=model, window=ScoringWindow.for_date(), user=self.user+ )+ anchored.assert_not_called()+ hogql.assert_not_called()++ def test_dry_run_and_live_run_take_the_same_route(self):+ pipeline, model = self._pipeline_and_model(_ANCHORS_RECIPE)+ scored = ScoredPopulation(rows=[{"distinct_id": "p1", "p_y": 0.5}], holdout_auc=0.66)+ with patch.object(scoring, "_score_via_anchors", return_value=scored) as anchored:+ result = score_population(+ team=self.team, pipeline=pipeline, model=model, window=ScoringWindow.for_date(), user=self.user+ )+ assert result == scored+ anchored.assert_called_once()++ @parameterized.expand([("bundle", "score_via_sandbox"), ("recipe", "_score_via_anchors")])+ def test_live_run_binds_every_query_to_the_start_of_the_day(self, _name, scorer):+ # Queries that each evaluate their own now() disagree on the anchors whenever a person+ # becomes eligible between them, and a retry under the same event UUIDs would score a+ # different population than the attempt it repeats.+ pipeline, model = self._pipeline_and_model(_ANCHORS_RECIPE)+ if scorer == "score_via_sandbox":+ model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"+ model.save(update_fields=["artifact_prefix"])+ with patch.object(scoring, scorer) as mocked:+ score_population(+ team=self.team, pipeline=pipeline, model=model, window=ScoringWindow.for_date(), user=self.user+ )+ assert mocked.call_args.kwargs["cutoff_ts"] == int(datetime(2026, 9, 11, tzinfo=UTC).timestamp())++ def test_a_retry_hours_later_gets_the_same_window(self):+ first = ScoringWindow.for_date()+ with time_machine.travel("2026-09-11T19:30:00Z", tick=False):+ retry = ScoringWindow.for_date()+ assert (retry.cutoff_ts, retry.is_backfill) == (first.cutoff_ts, first.is_backfill)++ def test_recipe_only_champion_records_its_holdout_auc(self):+ # Twenty labeled rows with a clean signal fit a real LogisticRegression; a column that+ # is null in the first row and text later must not be taken for a feature.+ pipeline, model = self._pipeline_and_model(_ANCHORS_RECIPE)+ training_rows = []+ for i in range(20):+ positive = i % 2+ training_rows.append(+ {+ "distinct_id": f"t{i}",+ "events_total": 40 + i if positive else i,+ "plan": None if i == 0 else "pro",+ "__label": positive,+ "__fold": i % 5,+ }+ )+ inference_rows = [+ {"distinct_id": "busy", "events_total": 55, "plan": "pro"},+ {"distinct_id": "quiet", "events_total": 1, "plan": None},+ ]+ with (+ patch.object(scoring, "_fetch_training_rows", return_value=training_rows),+ patch.object(scoring, "_fetch_inference_rows", return_value=inference_rows),+ patch.object(scoring, "_resolve_distinct_ids", return_value={}),+ patch.object(scoring, "capture_batch_internal", _capture_accepting_everything()),+ ):+ run = run_inference_for_pipeline(pipeline=pipeline, model=model)++ assert run.status == AutoresearchRun.Status.COMPLETED+ assert run.metrics["holdout_auc"] == 1.0+ dist = run.metrics["score_distribution"]+ assert dist["max"] > dist["min"]+++class TestQueryFailuresFailTheRun(TeamScopedTestMixin, BaseTest):+ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_feature_query_failure_fails_the_run(self, mock_run_hogql: MagicMock):+ # Returning no rows on a transient failure completed the run as an empty population+ # and advanced the cadence, so the day's scoring was skipped with nothing retried.+ mock_run_hogql.side_effect = Exception("clickhouse timeout")+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Failing", target_event="$pageview", horizon_days=7+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe=_STUB_RECIPE, recipe_hash="abc123"+ )++ with self.assertRaises(InferenceRunError):+ run_inference_for_pipeline(pipeline=pipeline, model=model)++ run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")+ assert run.status == AutoresearchRun.Status.FAILED+ pipeline.refresh_from_db()+ assert pipeline.last_scored_at is None+++class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):+ def _make_pipeline(self, inference_population: dict, target_event: str = "$pageview") -> AutoresearchPipeline:+ return AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="Test",+ target_event=target_event,+ horizon_days=7,+ inference_population=inference_population,+ )++ def _sent(self, mock_run: MagicMock) -> tuple[str, dict]:+ query = mock_run.call_args_list[0].kwargs["query"]+ return query.query, query.values++ @staticmethod+ def _feature_then_count(rows: list[list], count: int) -> list[HogQLResult]:+ return [HogQLResult(columns=["distinct_id"], rows=rows), HogQLResult(columns=["count()"], rows=[[count]])]++ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_population_is_applied_inside_the_bounded_query(self, mock_run: MagicMock):+ # Filtering the rows in Python after the bound meant a team with more people than the+ # cap failed every stub run, however small the configured population.+ pipeline = self._make_pipeline(+ {"properties": [{"key": "plan", "type": "person", "operator": "exact", "value": "pro"}]}+ )+ mock_run.side_effect = self._feature_then_count([["user-1"], ["user-3"]], count=2)++ rows = _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)++ assert {r["distinct_id"] for r in rows} == {"user-1", "user-3"}+ sql, values = self._sent(mock_run)+ assert "f.distinct_id IN (SELECT DISTINCT person_id FROM events WHERE" in sql+ assert "person.properties[{pop_k_0}] = {pop_0}" in sql+ assert values["pop_0"] == "pro"+ assert sql.rstrip().endswith(f"LIMIT {_MATERIALIZE_ROW_LIMIT}")+ count_query = mock_run.call_args_list[1].kwargs["query"]+ assert count_query.query.startswith("SELECT count() FROM (SELECT DISTINCT person_id FROM events WHERE")+ assert count_query.values["pop_0"] == "pro"+ assert all(call.kwargs["user"] == self.user for call in mock_run.call_args_list)++ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_empty_population_restricts_to_identified_users_within_the_window(self, mock_run: MagicMock):+ # v1 scores identified users only; the scan must skip the product's own event, or a+ # scored person stays eligible forever, and a future-dated event must not count.+ pipeline = self._make_pipeline({})+ mock_run.side_effect = self._feature_then_count([["user-1"]], count=1)++ _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)++ sql, values = self._sent(mock_run)+ assert "person.is_identified" in sql+ assert f"event != '{PREDICTION_EVENT_NAME}'" in sql+ assert "timestamp < now()" in sql+ assert values["lookback"] == 30++ @parameterized.expand(+ [+ (+ "ever_performed_event",+ {"kind": "ever_performed_event", "event": "downloaded_file"},+ ["person_id IN (SELECT DISTINCT person_id FROM events WHERE", "AND event = {popk_event})"],+ ),+ (+ "active_not_performed_target",+ {"kind": "active_not_performed_target", "active_within_days": 30},+ ["person_id NOT IN (SELECT DISTINCT person_id FROM events WHERE", "AND (event = {target}))"],+ ),+ (+ "performed_event_within_days",+ {"kind": "performed_event_within_days", "days": 30, "event": "downloaded_file"},+ ["toIntervalDay({popk_days})"],+ ),+ ]+ )+ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_population_kind_restricts_query(+ self, _name: str, population: dict, expected_fragments: list[str], mock_run: MagicMock+ ):+ # Template populations carry semantic kind specs; the stub path must compile them or+ # a template pipeline silently scores all identified users.+ pipeline = self._make_pipeline(population, target_event="downloaded_file")+ mock_run.side_effect = self._feature_then_count([["user-1"]], count=1)++ _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)++ sql, _values = self._sent(mock_run)+ for fragment in expected_fragments:+ assert fragment in sql++ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_uncompilable_population_kind_fails_before_any_query(self, mock_run: MagicMock):+ # Widening to "all identified users" is the failure mode being prevented.+ pipeline = self._make_pipeline({"kind": "ever_performed_event"})+ with self.assertRaises(ValueError):+ _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)+ mock_run.assert_not_called()++ @parameterized.expand(+ [+ ("blank_identifier", [["user-1"], [""]], 2),+ ("duplicate_person", [["user-1"], ["user-1"]], 2),+ ("dropped_member", [["user-1"]], 2),+ ]+ )+ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_rows_that_do_not_key_one_person_fail_the_run(self, _name, rows, population_count, mock_run: MagicMock):+ # A blank identifier was silently dropped and a duplicate emitted the same event UUID+ # twice; either way the run completed and reported a row count nobody received. Stub+ # SQL that drops a member leaves valid rows behind, so only the population count notices.+ pipeline = self._make_pipeline({})+ mock_run.side_effect = self._feature_then_count(rows, count=population_count)+ with self.assertRaises(InferenceRunError):+ _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)++ @parameterized.expand([("full_page", False), ("has_more", True)])+ @patch("products.autoresearch.backend.inference.scoring.run_hogql")+ def test_a_result_that_fills_the_bound_fails_the_run(self, _name: str, has_more: bool, mock_run: MagicMock):+ # HogQL silently caps an unbounded query at 100 rows, and a full result is almost+ # certainly truncated; scoring the partial set would skip users while the cadence advanced.+ pipeline = self._make_pipeline({})+ n = 1 if has_more else _MATERIALIZE_ROW_LIMIT+ mock_run.return_value = HogQLResult(+ columns=["distinct_id"], rows=[[f"person-{i}"] for i in range(n)], has_more=has_more+ )+ with self.assertRaises(InferenceRunError):+ _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)+++class TestResolveDistinctIds(TeamScopedTestMixin, BaseTest):+ def _pipeline(self) -> AutoresearchPipeline:+ return AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Identity", target_event="$pageview", horizon_days=7+ )++ @patch("products.autoresearch.backend.inference.scoring.get_persons_by_uuids")+ def test_maps_each_person_to_one_current_distinct_id_from_personhog(self, mock_persons: MagicMock):+ # An id read off event history can belong to someone else after a merge or split, so+ # the mapping has to come from the identity store, and a person with no id stays out.+ with_id, without_id, not_a_uuid = str(uuid4()), str(uuid4()), "person-1"+ mock_persons.return_value = [+ MagicMock(uuid=with_id, distinct_ids=["real-id"]),+ MagicMock(uuid=without_id, distinct_ids=[]),+ ]++ mapping = _resolve_distinct_ids(+ team=self.team, pipeline=self._pipeline(), person_ids=[with_id, without_id, not_a_uuid], user=self.user+ )++ assert mapping == {with_id: "real-id"}+ assert mock_persons.call_args.args == (self.team.pk, [with_id, without_id])+ assert mock_persons.call_args.kwargs == {"distinct_id_limit": 1}++ @patch("products.autoresearch.backend.inference.scoring.get_persons_by_uuids", side_effect=RuntimeError("down"))+ def test_identity_store_failure_fails_the_run(self, _mock: MagicMock):+ # Emitting every prediction person-less would leave the output property unset for the+ # whole population while the run reported success.+ with self.assertRaises(InferenceRunError):+ _resolve_distinct_ids(team=self.team, pipeline=self._pipeline(), person_ids=[str(uuid4())], user=self.user)+++class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):+ def _make_pipeline(self) -> AutoresearchPipeline:+ return AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="anchors", target_event="$pageview", horizon_days=7+ )++ def test_recipe_query_carries_explicit_limit_and_runs_fresh_as_the_user(self):+ # Without an explicit LIMIT, HogQL silently caps the composite query at 100 rows. A+ # cached result would score a stale population, and with no user HogQL fails closed.+ pipeline = self._make_pipeline()+ with (+ patch.object(scoring, "run_hogql") as mock_run_hogql,+ patch.object(scoring, "count_inference_anchors", return_value=0),+ ):+ mock_run_hogql.return_value = HogQLResult(columns=[], rows=[])+ _fetch_inference_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, cutoff_ts=None, user=self.user+ )+ sent = mock_run_hogql.call_args.kwargs+ assert sent["query"].query.rstrip().endswith(f"LIMIT {_MATERIALIZE_ROW_LIMIT}")+ assert sent["user"] == self.user+ assert sent["execution_mode"].name == "CALCULATE_BLOCKING_ALWAYS"+ assert sent["query"].modifiers is not None++ @parameterized.expand([("training",), ("inference",)])+ def test_recipe_query_hitting_row_limit_fails(self, kind: str):+ # A result that fills the LIMIT is a truncated population; completing would silently+ # skip the users past the cap while last_scored_at advances.+ pipeline = self._make_pipeline()+ full_page = HogQLResult(columns=["distinct_id"], rows=[[f"p{i}"] for i in range(3)])+ with (+ patch.object(scoring, "_MATERIALIZE_ROW_LIMIT", 3),+ patch.object(scoring, "run_hogql", return_value=full_page),+ patch.object(scoring, "count_inference_anchors", return_value=3),+ patch.object(scoring, "count_training_anchors", return_value=3),+ ):+ with self.assertRaises(InferenceRunError):+ if kind == "training":+ _fetch_training_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user+ )+ else:+ _fetch_inference_rows(+ team=self.team,+ pipeline=pipeline,+ feature_sql=_ANCHORS_FEATURE_SQL,+ cutoff_ts=None,+ user=self.user,+ )++ def test_inference_rows_thread_backfill_cutoff(self):+ # Backdated scoring must compute features as of the backfill instant, not now().+ pipeline = self._make_pipeline()+ with (+ patch.object(scoring, "run_hogql") as mock_run_hogql,+ patch.object(scoring, "count_inference_anchors", return_value=0) as count,+ ):+ mock_run_hogql.return_value = HogQLResult(columns=[], rows=[])+ _fetch_inference_rows(+ team=self.team,+ pipeline=pipeline,+ feature_sql=_ANCHORS_FEATURE_SQL,+ cutoff_ts=1_700_000_000,+ user=self.user,+ )+ assert mock_run_hogql.call_args.kwargs["query"].values["cutoff_ts"] == 1_700_000_000+ assert count.call_args.kwargs["cutoff_ts"] == 1_700_000_000++ @parameterized.expand(+ [+ ("duplicate_person", [["p1", 1, 0, 1], ["p1", 2, 1, 2]]),+ ("unlabeled_row", [["p1", 1, 0, 1], ["p2", 2, None, None]]),+ ]+ )+ def test_training_rows_that_do_not_key_one_labeled_person_fail_the_run(self, _name, rows):+ pipeline = self._make_pipeline()+ result = HogQLResult(columns=["distinct_id", "events_total", "__label", "__fold"], rows=rows)+ with (+ patch.object(scoring, "run_hogql", return_value=result),+ patch.object(scoring, "count_training_anchors", return_value=len(rows)),+ ):+ with self.assertRaises(InferenceRunError):+ _fetch_training_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user+ )++ def test_training_rows_that_drop_a_labeled_anchor_fail_the_run(self):+ # A join that loses anchors leaves unique, labeled rows behind, so only the count+ # against the labeled anchors notices the selection bias.+ pipeline = self._make_pipeline()+ result = HogQLResult(columns=["distinct_id", "events_total", "__label", "__fold"], rows=[["p1", 1, 0, 1]])+ with (+ patch.object(scoring, "run_hogql", return_value=result),+ patch.object(scoring, "count_training_anchors", return_value=2),+ ):+ with self.assertRaises(InferenceRunError):+ _fetch_training_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user+ )++ @parameterized.expand(+ [+ ("duplicate_columns", ["distinct_id", "n", "n"], ["p1", 1, 2]),+ ("too_many_columns_of_any_type", ["distinct_id", "a", "b", "c"], ["p1", "x", "y", "z"]),+ ]+ )+ def test_malformed_output_columns_fail_the_run(self, _name, columns, row):+ # A column set is checked as it is read: the numeric filter would discard string+ # columns after they were materialized, so a cap applied only to it never fires.+ pipeline = self._make_pipeline()+ result = HogQLResult(columns=columns, rows=[row])+ with (+ patch.object(scoring, "_MAX_FEATURE_COLS", 2),+ patch.object(scoring, "run_hogql", return_value=result),+ patch.object(scoring, "count_inference_anchors", return_value=1),+ ):+ with self.assertRaises(InferenceRunError):+ _fetch_inference_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, cutoff_ts=None, user=self.user+ )++ def test_inference_rows_that_drop_an_anchor_fail_the_run(self):+ # An inner join or a WHERE on the joined table drops people with every returned row+ # still looking valid; the anchor count is the only thing that notices.+ pipeline = self._make_pipeline()+ two_rows = HogQLResult(columns=["distinct_id"], rows=[["p1"], ["p2"]])+ with (+ patch.object(scoring, "run_hogql", return_value=two_rows),+ patch.object(scoring, "count_inference_anchors", return_value=3),+ ):+ with self.assertRaises(InferenceRunError):+ _fetch_inference_rows(+ team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, cutoff_ts=None, user=self.user+ )+++class TestRecipeFit(SimpleTestCase):+ @parameterized.expand(+ [+ ("seeded_from_the_pipeline", {}, 1234),+ ("recipe_seed_wins", {"random_state": 7}, 7),+ ]+ )+ def test_stochastic_estimator_gets_a_stable_seed(self, _name, params, expected):+ # A retry after a partial capture refits; two fits that disagree leave one cadence+ # with scores from both under the same event UUIDs.+ recipe = {"model_class": "sklearn.ensemble.RandomForestClassifier", "model_params": params}+ assert _estimator_for(recipe, seed=1234).random_state == expected++ def test_estimator_never_takes_every_core(self):+ # The fit runs in the worker process, so an agent's n_jobs=-1 would starve everything else on it.+ recipe = {"model_class": "sklearn.ensemble.RandomForestClassifier", "model_params": {"n_jobs": -1}}+ assert _estimator_for(recipe, seed=1).n_jobs == 1++ def test_training_row_order_does_not_change_the_fit(self):+ recipe = {+ "model_class": "sklearn.ensemble.RandomForestClassifier",+ "model_params": {"n_estimators": 5, "max_depth": 2},+ }+ training_rows = [+ {+ "distinct_id": f"t{i:02d}",+ "x": i % 8,+ "y": (i * 3) % 8,+ "__label": int((i % 8 > 3) ^ ((i * 3) % 8 > 3)),+ "__fold": i % 5,+ }+ for i in range(40)+ ]+ inference_rows = [{"distinct_id": f"s{i}", "x": i, "y": (i * 3) % 8} for i in range(8)]+ forward = _fit_on_training_predict_on_inference(+ training_rows=training_rows, inference_rows=inference_rows, recipe=recipe, pipeline_id="p"+ )+ backward = _fit_on_training_predict_on_inference(+ training_rows=training_rows[::-1], inference_rows=inference_rows, recipe=recipe, pipeline_id="p"+ )+ assert [r["p_y"] for r in forward.rows] == [r["p_y"] for r in backward.rows]++ def test_too_many_feature_columns_fail_before_any_matrix_is_built(self):+ rows = [{"distinct_id": f"p{i}", "a": 1, "b": 2, "c": 3, "__label": i % 2, "__fold": i % 5} for i in range(10)]+ with patch.object(scoring, "_MAX_FEATURE_COLS", 2):+ with self.assertRaises(InferenceRunError):+ _fit_on_training_predict_on_inference(+ training_rows=rows, inference_rows=rows[:2], recipe=_ANCHORS_RECIPE, pipeline_id="p"+ )diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.pyindex 2e1d28f3d1cc..ff03ae1c4fc2 100644--- a/products/autoresearch/backend/inference/test_sandbox_inference.py+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py@@ -11,6 +11,7 @@ from django.test import SimpleTestCaseimport pandas as pdfrom parameterized import parameterized+from posthog.api.capture import CaptureInternalResultfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.user import User@@ -34,7 +35,8 @@ from products.autoresearch.backend.inference.sandbox import (materialize_training_data,score_via_sandbox,)-from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.inference.scoring import run_inference_for_pipeline+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRunfrom products.autoresearch.backend.query import HogQLResultfrom products.autoresearch.backend.testing import TeamScopedTestMixinfrom products.autoresearch.backend.training.artifacts import ArtifactBundle, BundleNotFound@@ -141,7 +143,10 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):def test_training_data_splits_folds_and_extracts_feature_cols(self):pipeline = self._pipeline()- with patch.object(sandbox_inference, "_materialize_rows", return_value=_TRAINING_ROWS):+ with (+ patch.object(sandbox_inference, "count_training_anchors", return_value=len(_TRAINING_ROWS)),+ patch.object(sandbox_inference, "_materialize_rows", return_value=_TRAINING_ROWS),+ ):data = materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")assert data.feature_cols == ["events_total", "pageviews"]@@ -150,19 +155,26 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):@parameterized.expand([- ("duplicate_person", [{"distinct_id": "p1", "__label": 1, "__fold": 1}] * 2),- ("no_label_match", [{"distinct_id": "p1", "__label": None, "__fold": None}]),+ ("duplicate_person", [{"distinct_id": "p1", "__label": 1, "__fold": 1}] * 2, 1),+ ("no_label_match", [{"distinct_id": "p1", "__label": None, "__fold": None}], 1),+ ("dropped_anchor", [{"distinct_id": "p1", "__label": 1, "__fold": 1}], 2),])- def test_training_data_rejects_rows_that_do_not_key_one_labeled_person(self, _name, rows):+ def test_training_data_rejects_rows_that_do_not_key_every_labeled_anchor_once(self, _name, rows, anchors):pipeline = self._pipeline()- with patch.object(sandbox_inference, "_materialize_rows", return_value=rows):+ with (+ patch.object(sandbox_inference, "count_training_anchors", return_value=anchors),+ patch.object(sandbox_inference, "_materialize_rows", return_value=rows),+ ):with self.assertRaises(SandboxInferenceError):materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")def test_score_data_is_inference_only_no_labels(self):pipeline = self._pipeline()- with patch.object(sandbox_inference, "_materialize_rows", return_value=_SCORE_ROWS) as run:+ with (+ patch.object(sandbox_inference, "count_inference_anchors", return_value=len(_SCORE_ROWS)),+ patch.object(sandbox_inference, "_materialize_rows", return_value=_SCORE_ROWS) as run,+ ):score_rows = _materialize_score_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")@@ -171,9 +183,20 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):assert run.call_count == 1assert [r["distinct_id"] for r in score_rows] == ["s1", "s2"]- def test_score_data_rejects_duplicate_persons(self):+ @parameterized.expand(+ [+ ("duplicate_persons", [_SCORE_ROWS[0]] * 2, 1),+ ("dropped_anchor", [_SCORE_ROWS[0]], 2),+ ]+ )+ def test_score_data_rejects_rows_that_do_not_key_every_anchor_once(self, _name, rows, anchor_count):+ # A dropped anchor is invisible in the rows themselves: an inner join in features.sql+ # returns only valid-looking rows, and the person it lost is never scored again.pipeline = self._pipeline()- with patch.object(sandbox_inference, "_materialize_rows", return_value=[_SCORE_ROWS[0]] * 2):+ with (+ patch.object(sandbox_inference, "count_inference_anchors", return_value=anchor_count),+ patch.object(sandbox_inference, "_materialize_rows", return_value=rows),+ ):with self.assertRaises(SandboxInferenceError):_materialize_score_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")@@ -519,8 +542,8 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):score_via_sandbox(team=self.team, pipeline=pipeline, model=model)materialize.assert_not_called()- with self.assertRaises(SandboxInferenceError): # no rows, after materialization ran as the user- score_via_sandbox(team=self.team, pipeline=pipeline, model=model, user=self.user)+ result = score_via_sandbox(team=self.team, pipeline=pipeline, model=model, user=self.user)+ assert result.scored_rows == [] # materialization ran, as the explicit userassert materialize.call_args.kwargs["user"] == self.userdef test_predict_failure_raises_and_destroys_sandbox(self):@@ -553,8 +576,11 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):assert not fake.ran("predict.py")assert fake.destroyed is True- def test_empty_score_rows_raises_before_sandbox(self):+ def test_empty_population_completes_with_no_rows_and_no_sandbox(self):+ # A population that matches nobody is a real zero; the recipe path completes it too.pipeline, model = self._pipeline_and_model()+ model.holdout_score = 0.61+ model.save(update_fields=["holdout_score"])create_mock = MagicMock()with (patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),@@ -563,9 +589,10 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):patch.object(sandbox_inference, "_materialize_score_data", return_value=[]),patch.object(sandbox_inference.Sandbox, "create", create_mock),):- with self.assertRaises(SandboxInferenceError):- score_via_sandbox(team=self.team, pipeline=pipeline, model=model)- create_mock.assert_not_called() # cheap guard fires before paying for a sandbox+ result = score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ assert result.scored_rows == []+ assert result.holdout_auc == 0.61+ create_mock.assert_not_called()def test_fit_champion_model_trains_smoke_tests_predict_and_persists(self):pipeline, model = self._pipeline_and_model()@@ -628,3 +655,63 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):fit_champion_model(team=self.team, pipeline=pipeline, prefix=model.artifact_prefix)write_model.assert_not_called()assert fake.destroyed is True+++class TestInferenceRouting(TeamScopedTestMixin, BaseTest):+ def _pipeline_and_bundle_model(self):+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="routing",+ target_event="downloaded_file",+ horizon_days=7,+ output_person_property="predicted_p_download",+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ recipe_hash="fixture",+ model_recipe={},+ artifact_prefix="tasks/autoresearch/team_1/pipeline_x/run_y",+ )+ return pipeline, model++ def test_bundle_model_routes_to_sandbox_and_records_metrics(self):+ pipeline, model = self._pipeline_and_bundle_model()+ sandbox_result = SandboxScoreResult(+ scored_rows=[{"distinct_id": "s1", "p_y": 0.8}, {"distinct_id": "s2", "p_y": 0.2}],+ holdout_auc=0.71,+ n_train=2,+ n_features=2,+ )+ emit = MagicMock(+ side_effect=lambda **kwargs: CaptureInternalResult(+ status_code=200, ok=[e["event_uuid"] for e in kwargs["events"]]+ )+ )+ with (+ patch("products.autoresearch.backend.inference.scoring.score_via_sandbox", return_value=sandbox_result),+ patch("products.autoresearch.backend.inference.scoring._resolve_distinct_ids", return_value={}),+ patch("products.autoresearch.backend.inference.scoring.capture_batch_internal", emit),+ ):+ run = run_inference_for_pipeline(pipeline=pipeline, model=model)++ assert run.status == AutoresearchRun.Status.COMPLETED+ assert run.rows_scored == 2+ assert run.metrics["sandbox"] is True+ assert run.metrics["holdout_auc"] == 0.71+ assert emit.call_count == 1+ assert len(emit.call_args.kwargs["events"]) == 2++ def test_sandbox_failure_marks_run_failed_with_error(self):+ pipeline, model = self._pipeline_and_bundle_model()+ with patch(+ "products.autoresearch.backend.inference.scoring.score_via_sandbox",+ side_effect=SandboxInferenceError("train.py failed"),+ ):+ with self.assertRaises(SandboxInferenceError):+ run_inference_for_pipeline(pipeline=pipeline, model=model)++ run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")+ assert run.status == AutoresearchRun.Status.FAILED+ assert "train.py failed" in run.errordiff --git a/products/autoresearch/backend/management/AGENTS.md b/products/autoresearch/backend/management/AGENTS.mdindex 25a3a8c28610..a0d6b619ae4f 100644--- a/products/autoresearch/backend/management/AGENTS.md+++ b/products/autoresearch/backend/management/AGENTS.md@@ -2,7 +2,7 @@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.+This package landed with `autoresearch_validate` and `autoresearch_score` only. `autoresearch_train` 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.@@ -15,8 +15,9 @@ Every command calls the same functions the API and the Temporal activities call.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.+ `--pipeline-id --user-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. They are mutually exclusive; a future date or a non-positive window is refused before anything runs.+ `--dry-run` scores through the champion's real path (sandbox or recipe), applies the same prediction-date guards as a live run, and prints the distribution without emitting. `--seed-fixture-bundle` uploads the fixture bundle, fits it through `fit_champion_model()` (so it needs a sandbox provider), and only then swaps it in as champion, because scoring loads the persisted `model.pkl` and never fits. `--user-id` is the person HogQL applies access control for; without it the queries run as the pipeline's creator.- `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.@@ -42,7 +43,7 @@ The env var is needed because flox only sources `.env` on first activation, so t- **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 backfill older than the team's `drop_events_older_than` is refused**, because ingestion would accept and then drop the events.- 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.diff --git a/products/autoresearch/backend/management/commands/autoresearch_score.py b/products/autoresearch/backend/management/commands/autoresearch_score.pynew file mode 100644index 000000000000..10c1cda6ff86--- /dev/null+++ b/products/autoresearch/backend/management/commands/autoresearch_score.py@@ -0,0 +1,229 @@+"""+Run inference for an autoresearch pipeline: score the population and emit+autoresearch_prediction events through capture.++Usage:+ python manage.py autoresearch_score --pipeline-id <uuid>++Requires:+ - PostHog running locally (./bin/start or hogli start)+ - Demo data generated (python manage.py generate_demo_data or similar)+ - A champion model in place (run autoresearch_train first)++The events appear in the team's events table under the event name+'autoresearch_prediction' with properties prefixed '$autoresearch_*'.+"""++from datetime import date, timedelta+from pathlib import Path++from django.core.management.base import BaseCommand, CommandError+from django.db import transaction+from django.utils import timezone++from posthog.models.scoping import team_scope+from posthog.models.user import User++from products.autoresearch.backend.inference.sandbox import fit_champion_model+from products.autoresearch.backend.inference.scoring import (+ ScoredPopulation,+ ScoringWindow,+ _summarize_scores,+ run_inference_for_pipeline,+ score_population,+)+from products.autoresearch.backend.management.scoping import resolve_pipeline+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.training.artifacts import ArtifactBundle, bundle_prefix, write_bundle++_FIXTURE_BUNDLE_DIR = Path(__file__).resolve().parents[2] / "test_fixtures" / "bundle"+++class Command(BaseCommand):+ help = "Score the inference population for a pipeline and emit autoresearch_prediction events."++ def add_arguments(self, parser):+ parser.add_argument("--pipeline-id", type=str, required=True, help="UUID of the pipeline to score.")+ parser.add_argument(+ "--user-id",+ type=int,+ default=None,+ help="Run the queries as this user. Defaults to the pipeline's creator.",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Score the population through the champion's normal path but do not emit events.",+ )+ parser.add_argument(+ "--seed-fixture-bundle",+ action="store_true",+ help=(+ "Upload the reference fixture bundle to object storage and create/point a champion "+ "model at it, then score via the sandbox path. For proving inference-in-sandbox locally."+ ),+ )+ dates = parser.add_mutually_exclusive_group()+ dates.add_argument(+ "--prediction-date",+ type=str,+ default=None,+ help="Backfill: score as of this past date (YYYY-MM-DD) instead of today. Features are "+ "computed as of that date and events are emitted with that date's timestamp.",+ )+ dates.add_argument(+ "--backfill-days",+ type=int,+ default=None,+ help="Backfill the last N days (one scoring run per day, ending yesterday). Useful to "+ "populate online validation without waiting a full horizon for predictions to mature.",+ )++ def handle(self, *args, **options):+ pipeline = resolve_pipeline(options["pipeline_id"])+ user = self._resolve_user(options["user_id"])+ prediction_dates = self._resolve_prediction_dates(options)+ with team_scope(pipeline.team_id):+ self._run(pipeline, user, prediction_dates, options)++ @staticmethod+ def _resolve_user(user_id: int | None) -> User | None:+ if user_id is None:+ return None+ try:+ return User.objects.get(pk=user_id)+ except User.DoesNotExist:+ raise CommandError(f"User {user_id} not found.")++ def _run(self, pipeline: AutoresearchPipeline, user: User | None, prediction_dates: list[date], options):+ champion: AutoresearchModel | None+ if options["seed_fixture_bundle"]:+ champion = self._seed_fixture_bundle(pipeline, user)+ else:+ champion = (+ AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)+ .order_by("-created_at")+ .first()+ )+ if not champion:+ raise CommandError(f"No champion model found for pipeline {pipeline.pk}. Run autoresearch_train first.")++ self.stdout.write(f"\nRunning inference for pipeline '{pipeline.name}' ({pipeline.pk})")+ self.stdout.write(f" Target : {pipeline.target_event}")+ self.stdout.write(f" Horizon : {pipeline.horizon_days} days")+ self.stdout.write(f" Champion model : {champion.pk}")+ self.stdout.write(f" Holdout AUC : {champion.holdout_score}")+ if champion.artifact_prefix:+ self.stdout.write(f" Bundle prefix : {champion.artifact_prefix}")+ else:+ self.stdout.write(f" Stub recipe : {(champion.model_recipe or {}).get('stub', False)}")+ self.stdout.write(f" Output prop : {pipeline.output_person_property}")+ self.stdout.write("")++ if len(prediction_dates) > 1:+ self.stdout.write(+ f"Backfilling {len(prediction_dates)} dates: {prediction_dates[0]} to {prediction_dates[-1]}\n"+ )+ labelled = len(prediction_dates) > 1 or options.get("prediction_date")++ if options["dry_run"]:+ self.stdout.write(self.style.WARNING("Dry run: scoring through the champion's path, not emitting.\n"))+ for prediction_date in prediction_dates:+ scored = score_population(+ team=pipeline.team,+ pipeline=pipeline,+ model=champion,+ window=ScoringWindow.for_date(prediction_date),+ user=user,+ )+ self._print_scores(scored, label=f"[{prediction_date}] " if labelled else "")+ return++ for prediction_date in prediction_dates:+ run = run_inference_for_pipeline(+ pipeline=pipeline, model=champion, prediction_date=prediction_date, user=user+ )+ label = f"[{prediction_date}] " if labelled else ""+ self.stdout.write(f"{label}Run ID : {run.pk}")+ self.stdout.write(f"{label}Status : {run.status}")+ self.stdout.write(f"{label}Rows scored : {run.rows_scored}")+ if run.metrics.get("score_distribution"):+ dist = run.metrics["score_distribution"]+ self.stdout.write(+ f" dist: count={dist.get('count')} mean={dist.get('mean')} "+ f"p10={dist.get('p10')} p50={dist.get('p50')} p90={dist.get('p90')}"+ )+ if run.status == "completed":+ self.stdout.write(self.style.SUCCESS(f" Emitted {run.rows_scored} autoresearch_prediction events."))+ else:+ self.stdout.write(self.style.ERROR(f" Run failed: {run.error}"))++ self.stdout.write(+ f"\nQuery in PostHog: SELECT distinct_id, properties.$autoresearch_p_y "+ f"FROM events WHERE event = 'autoresearch_prediction' "+ f"AND properties.$autoresearch_pipeline_id = '{pipeline.pk}' ORDER BY timestamp DESC LIMIT 20"+ )++ def _print_scores(self, scored: ScoredPopulation, *, label: str) -> None:+ self.stdout.write(f"{label}Rows scored : {len(scored.rows)}")+ if not scored.rows:+ return+ self.stdout.write(f"{label}Columns : {[k for k in scored.rows[0].keys() if k != 'p_y']}")+ dist = _summarize_scores([row["p_y"] for row in scored.rows])+ self.stdout.write(+ f"{label}Scores : min={dist['min']} p50={dist['p50']} max={dist['max']} mean={dist['mean']}"+ )+ if scored.holdout_auc is not None:+ self.stdout.write(f"{label}Holdout AUC : {scored.holdout_auc}")++ @staticmethod+ def _resolve_prediction_dates(options: dict) -> list[date]:+ """The dates to score: a backfill window ending yesterday, one past date, or today."""+ today = date.today()+ backfill_days = options.get("backfill_days")+ if backfill_days is not None:+ if backfill_days < 1:+ raise CommandError("--backfill-days must be at least 1.")+ # Oldest first so online validation reads a chronological history.+ return [today - timedelta(days=d) for d in range(backfill_days, 0, -1)]+ raw_date = options.get("prediction_date")+ if raw_date:+ try:+ prediction_date = date.fromisoformat(raw_date)+ except ValueError:+ raise CommandError(f"--prediction-date must be YYYY-MM-DD, got {raw_date!r}.")+ if prediction_date > today:+ raise CommandError(f"--prediction-date {prediction_date} is in the future; scoring runs as of today.")+ return [prediction_date]+ return [today]++ def _seed_fixture_bundle(self, pipeline: AutoresearchPipeline, user: User | None) -> AutoresearchModel:+ """Upload the reference fixture bundle, fit it, and make a fresh model pointing at it the champion."""+ bundle = ArtifactBundle.from_dir(_FIXTURE_BUNDLE_DIR)+ # The upload and the fit happen before any champion is archived, so a storage or+ # sandbox failure leaves the pipeline with the champion it had. Scoring loads the+ # persisted model.pkl and never fits, so an unfitted bundle would fail every cadence.+ model = AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHALLENGER,+ recipe_hash="fixture",+ model_recipe={},+ agent_description="fixture bundle (slice 1)",+ is_preliminary=True,+ )+ prefix = bundle_prefix(team_id=pipeline.team_id, pipeline_id=str(pipeline.pk), training_run_id=str(model.pk))+ write_bundle(prefix, bundle)+ metrics = fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix, bundle=bundle, user=user)+ model.holdout_score = metrics.get("holdout_auc")+ model.metrics = metrics+ now = timezone.now()+ with transaction.atomic():+ AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).update(+ role=AutoresearchModel.Role.ARCHIVED, archived_at=now+ )+ model.role = AutoresearchModel.Role.CHAMPION+ model.artifact_prefix = prefix+ model.promoted_at = now+ model.save(update_fields=["role", "artifact_prefix", "promoted_at", "holdout_score", "metrics"])+ self.stdout.write(self.style.SUCCESS(f"Seeded and fitted the fixture bundle at {prefix}"))+ return modeldiff --git a/products/autoresearch/backend/management/scoping.py b/products/autoresearch/backend/management/scoping.pynew file mode 100644index 000000000000..6ea393c13d7d--- /dev/null+++ b/products/autoresearch/backend/management/scoping.py@@ -0,0 +1,16 @@+from django.core.management.base import CommandError++from products.autoresearch.backend.models import AutoresearchPipeline+++def resolve_pipeline(pipeline_id: str) -> AutoresearchPipeline:+ """Look up a pipeline by id, before any team scope is known.++ A CLI operator supplies a pipeline id, not a team, so this one read is+ deliberately cross-team. Every caller enters the pipeline's team scope for+ the work that follows.+ """+ try:+ return AutoresearchPipeline.objects.unscoped().select_related("team").get(pk=pipeline_id)+ except AutoresearchPipeline.DoesNotExist:+ raise CommandError(f"Pipeline {pipeline_id} not found.")diff --git a/products/autoresearch/backend/management/test_autoresearch_score.py b/products/autoresearch/backend/management/test_autoresearch_score.pynew file mode 100644index 000000000000..377ca3d7d9b8--- /dev/null+++ b/products/autoresearch/backend/management/test_autoresearch_score.py@@ -0,0 +1,87 @@+from datetime import date, timedelta++import time_machine+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 django.test import SimpleTestCase++from parameterized import parameterized++from products.autoresearch.backend.inference.sandbox import SandboxInferenceError+from products.autoresearch.backend.management.commands import autoresearch_score+from products.autoresearch.backend.management.commands.autoresearch_score import Command+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.testing import TeamScopedTestMixin+++@time_machine.travel("2026-09-11T12:00:00Z", tick=False)+class TestResolvePredictionDates(SimpleTestCase):+ @parameterized.expand(+ [+ ("zero_backfill_days_ran_live", {"backfill_days": 0}),+ ("negative_backfill_days_scored_nothing", {"backfill_days": -3}),+ ("future_date_read_as_live", {"prediction_date": "2026-09-12"}),+ ("unparseable_date", {"prediction_date": "yesterday"}),+ ]+ )+ def test_rejects_windows_that_would_score_the_wrong_days(self, _name, options):+ with self.assertRaises(CommandError):+ Command._resolve_prediction_dates(options)++ def test_backfill_window_ends_yesterday_oldest_first(self):+ dates = Command._resolve_prediction_dates({"backfill_days": 3})+ today = date.today()+ assert dates == [today - timedelta(days=3), today - timedelta(days=2), today - timedelta(days=1)]+++class TestSeedFixtureBundle(TeamScopedTestMixin, BaseTest):+ def _pipeline_with_champion(self):+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="seed", target_event="$pageview", horizon_days=7+ )+ champion = AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={"stub": True}, recipe_hash="old"+ )+ return pipeline, champion++ @parameterized.expand(+ [+ ("upload_fails", "write_bundle", OSError("storage down")),+ ("fit_fails", "fit_champion_model", SandboxInferenceError("train.py failed")),+ ]+ )+ def test_a_failed_step_leaves_the_current_champion_in_place(self, _name, step, error):+ pipeline, champion = self._pipeline_with_champion()+ with (+ patch.object(autoresearch_score, "write_bundle"),+ patch.object(autoresearch_score, "fit_champion_model"),+ patch.object(autoresearch_score, step, side_effect=error),+ ):+ with self.assertRaises(type(error)):+ call_command("autoresearch_score", "--pipeline-id", str(pipeline.pk), "--seed-fixture-bundle")+ champion.refresh_from_db()+ assert champion.role == AutoresearchModel.Role.CHAMPION+ assert (+ not AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)+ .exclude(pk=champion.pk)+ .exists()+ )++ def test_the_fitted_fixture_becomes_champion_with_its_metrics(self):+ pipeline, old_champion = self._pipeline_with_champion()+ metrics = {"holdout_auc": 0.81, "n_train": 40, "n_features": 6}+ with (+ patch.object(autoresearch_score, "write_bundle"),+ patch.object(autoresearch_score, "fit_champion_model", return_value=metrics) as fit,+ patch.object(autoresearch_score, "run_inference_for_pipeline") as run,+ ):+ run.return_value.status = "completed"+ run.return_value.metrics = {}+ call_command("autoresearch_score", "--pipeline-id", str(pipeline.pk), "--seed-fixture-bundle")+ new_champion = AutoresearchModel.objects.get(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)+ assert new_champion.pk != old_champion.pk+ assert new_champion.holdout_score == 0.81+ assert fit.call_args.kwargs["prefix"] == new_champion.artifact_prefixdiff --git a/products/autoresearch/backend/test_fixtures/bundle/features.sql b/products/autoresearch/backend/test_fixtures/bundle/features.sqlnew file mode 100644index 000000000000..9fbeaa88f329--- /dev/null+++ b/products/autoresearch/backend/test_fixtures/bundle/features.sql@@ -0,0 +1,24 @@+-- Reference feature SQL (fixture bundle, slice 1).+-- The framework substitutes the anchors placeholder with a per-user+-- (person_id, cutoff_ts) table (per-user T0 at training, now at inference) and+-- the lookback-days placeholder with the rolling-window size. Events are read+-- strictly before each user's cutoff_ts so features never peek into the label+-- window. NOTE: do not write the literal placeholder tokens in comments — the+-- framework string-substitutes them everywhere, including inside comments.+SELECT+ a.person_id AS distinct_id,+ count(e.uuid) AS events_total,+ uniqIf(e.event, e.event NOT LIKE '$%') AS unique_user_events,+ countIf(e.event = '$pageview') AS pageviews,+ countIf(e.event = 'uploaded_file') AS uploads,+ countIf(e.event = 'downloaded_file') AS downloads,+ dateDiff('day', max(e.timestamp), fromUnixTimestamp(a.cutoff_ts)) AS days_since_last_event+FROM {anchors} a+LEFT JOIN events e+ ON e.person_id = a.person_id+ AND e.event != 'autoresearch_prediction'+ AND e.timestamp < fromUnixTimestamp(a.cutoff_ts)+ AND e.timestamp >= fromUnixTimestamp(a.cutoff_ts) - toIntervalDay({lookback_days})+-- cutoff_ts is 1:1 with person_id; include it in GROUP BY so ClickHouse allows+-- selecting it (no functional-dependency inference like Postgres). Still one row per person.+GROUP BY a.person_id, a.cutoff_tsdiff --git a/products/autoresearch/backend/test_fixtures/bundle/predict.py b/products/autoresearch/backend/test_fixtures/bundle/predict.pynew file mode 100644index 000000000000..e0dfe7fbc125--- /dev/null+++ b/products/autoresearch/backend/test_fixtures/bundle/predict.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+"""+Reference autoresearch prediction script (fixture bundle, slice 1).++Contract with the framework:+ python predict.py <score_features.parquet> <model.pkl> <scores.parquet>++ - Loads the pickled {"model", "feature_cols"} produced by train.py.+ - Aligns the score features to the trained feature columns (missing -> 0).+ - Writes <scores.parquet> with columns `distinct_id,p_y`.+ - Prints NOTHING to stdout — the framework reads scores.parquet back (base64+ over `cat`), so stray stdout would corrupt the parse.+"""++from __future__ import annotations++import sys+import pickle++import pandas as pd+++def main() -> int:+ score_features_path, model_path, scores_out = sys.argv[1], sys.argv[2], sys.argv[3]++ # The pickle was written by train.py in this same sandbox from bytes the framework+ # persisted and read back as opaque; nothing outside the sandbox unpickles it.+ with open(model_path, "rb") as f:+ bundle = pickle.load(f) # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle+ model = bundle["model"]+ feature_cols = bundle["feature_cols"]++ features = pd.read_parquet(score_features_path)+ x = features.reindex(columns=feature_cols, fill_value=0).fillna(0).astype(float)+ p_y = model.predict_proba(x.to_numpy())[:, 1]++ out = pd.DataFrame({"distinct_id": features["distinct_id"], "p_y": p_y.round(6)})+ out.to_parquet(scores_out, index=False)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/products/autoresearch/backend/test_fixtures/bundle/train.py b/products/autoresearch/backend/test_fixtures/bundle/train.pynew file mode 100644index 000000000000..64b2320df38c--- /dev/null+++ b/products/autoresearch/backend/test_fixtures/bundle/train.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""+Reference autoresearch training script (fixture bundle, slice 1).++Contract with the framework:+ python train.py <train_features.parquet> <train_labels.parquet> <model.pkl> <output.json> \+ [<holdout_features.parquet> <holdout_labels.parquet>] [--random-state N]++ - Features parquet: first column `distinct_id`, remaining columns numeric features.+ - Labels parquet: columns `distinct_id`, `__label` (0/1).+ - Fits a sklearn pipeline on (train features ⋈ train labels), pickles it to <model.pkl>.+ - If holdout files are given and the holdout has >=2 label classes, computes holdout AUC.+ - Writes a structured metrics file to <output.json>:+ {"holdout_auc": <float|null>, "n_train": <int>, "n_features": <int>}+ The framework reads and validates this file — nothing is parsed from stdout.+ - Exits non-zero on degenerate data (too few positives/negatives) so the framework+ fails the run instead of shipping a useless model.++The framework runs the feature SQL and grades realized AUC; this script only fits + reports.+"""++from __future__ import annotations++import sys+import json+import pickle+import argparse+from dataclasses import dataclass++import pandas as pd+from sklearn.linear_model import LogisticRegression+from sklearn.metrics import roc_auc_score++MIN_PER_CLASS = 5+++@dataclass(frozen=True)+class _LabeledMatrix:+ x: pd.DataFrame+ y: pd.Series+ feature_cols: list[str]+++def _load_xy(features_path: str, labels_path: str) -> _LabeledMatrix:+ features = pd.read_parquet(features_path)+ labels = pd.read_parquet(labels_path)+ merged = features.merge(labels[["distinct_id", "__label"]], on="distinct_id", how="inner")+ feature_cols = [c for c in features.columns if c != "distinct_id"]+ x = pd.DataFrame(merged[feature_cols]).fillna(0).astype(float)+ y = pd.Series(merged["__label"]).fillna(0).astype(int)+ return _LabeledMatrix(x=x, y=y, feature_cols=feature_cols)+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("train_features")+ parser.add_argument("train_labels")+ parser.add_argument("model_out")+ parser.add_argument("output_json")+ parser.add_argument("holdout_features", nargs="?", default=None)+ parser.add_argument("holdout_labels", nargs="?", default=None)+ parser.add_argument("--random-state", type=int, default=42)+ args = parser.parse_args()++ train = _load_xy(args.train_features, args.train_labels)+ x_train, y_train, feature_cols = train.x, train.y, train.feature_cols++ n_pos = int(y_train.sum())+ n_neg = int(len(y_train) - n_pos)+ if n_pos < MIN_PER_CLASS or n_neg < MIN_PER_CLASS:+ print(f"degenerate training data: n_pos={n_pos} n_neg={n_neg}", file=sys.stderr) # noqa: T201+ return 1++ model = LogisticRegression(C=1.0, max_iter=200, random_state=args.random_state)+ model.fit(x_train.to_numpy(), y_train.to_numpy())++ # This script runs inside the sandbox and only predict.py, in the same sandbox, reads the+ # pickle back; the framework treats model.pkl as opaque bytes and never unpickles it.+ artifact = {"model": model, "feature_cols": feature_cols}+ with open(args.model_out, "wb") as f:+ pickle.dump(artifact, f) # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle++ holdout_auc: float | None = None+ if args.holdout_features and args.holdout_labels:+ holdout = _load_xy(args.holdout_features, args.holdout_labels)+ x_hold, y_hold = holdout.x, holdout.y+ if len(x_hold) and y_hold.nunique() >= 2:+ x_hold = x_hold.reindex(columns=feature_cols, fill_value=0)+ p_hold = model.predict_proba(x_hold.to_numpy())[:, 1]+ holdout_auc = float(roc_auc_score(y_hold.to_numpy(), p_hold))++ with open(args.output_json, "w") as f:+ json.dump(+ {+ "holdout_auc": round(holdout_auc, 4) if holdout_auc is not None else None,+ "n_train": int(len(y_train)),+ "n_features": len(feature_cols),+ },+ f,+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())